簡體   English   中英

如何在一行中控制台記錄 object

[英]how to console.log object in one line

我想修改這個 object

 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)

我想得到這個 output 我怎么能把它放在一行和一個字符串中? 或者我應該使用新的 function 嗎?

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

要獲得您說過想要的 output,您必須:

  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));

最快的[使用 for-in 循環]:

 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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM