如何在一行中控制台.log对象



我想修改这个对象

const myObject = { "first": ["x","y", "z"], "second": ["a", "b"], "third": ["c"] }
const string = "String!";
const count = () => {
const result = Object.entries(myObject ).forEach(([key, value]) =>
console.log(`${key} ${value.length > 1 ? ("x " + value.length) : ""} (${value})`)
);
return result;
};
count();

我到了

first x 3 (x, y, z)
second x 2 (a, b) 
third (c)

我想得到这个输出,我怎么能把它放在一行和字符串之前?还是应该使用新功能?

String! first x 3 (x, y, z) – second x 2 (a, b) - third(c)

要获得您所说的输出,您必须:

  1. 使用map构建条目数组,而不是输出这些字符串。

  2. string添加到开头。

  3. 将数组转换为条目之间带有" - "的字符串,可能是通过join(" - ")

我还建议将myObject作为参数传递到count中,而不是直接使用它:

实例:

const myObject = { "first": ["x","y", "z"], "second": ["a", "b"], "third": ["c"] }
const string = "String!";
const count = (obj) => {
const result = Object.entries(obj).map(([key, value]) =>
`${key} ${value.length > 1 ? ("x " + value.length) : ""} (${value})`
);
return result;
};
console.log(string + " " + count(myObject).join(" - "));

或者,如果您想在count中执行,也可以传入string:

const myObject = { "first": ["x","y", "z"], "second": ["a", "b"], "third": ["c"] }
const string = "String!";
const count = (obj, str) => {
const result = Object.entries(obj).map(([key, value]) =>
`${key} ${value.length > 1 ? ("x " + value.length) : ""} (${value})`
);
return `${str} ${result.join(" - ")}`;
};
console.log(count(myObject, string));

您可以使用reduce方法,并连接所有值。它将是map and join的组合。是所有API中最简单、速度更快的。

const count = (prefix, obj) => {
const result = Object.entries(obj).reduce(
(str, [key, value]) =>
(str += ` ${key} ${
value.length > 1 ? "X " + value.length : ""
} (${value})`),
prefix
);
return result;
};
const myObject = { first: ["x", "y", "z"], second: ["a", "b"], third: ["c"] };
const string = "String!";
console.log(count(string, myObject));

所有[用于循环中]中最快的:

const count = (obj, prefix = "") => {
for (let key in obj) {
let value = obj[key];
prefix +=
value && value.length > 1
? ` ${key} X ${value.length} (${value})`
: ` ${key} (${value})`;
}
return prefix;
};
const myObject = { first: ["x", "y", "z"], second: ["a", "b"], third: ["c"] };
const string = "String!";
console.log(count(myObject, string));

最新更新