簡體   English   中英

從對象數組返回 object

[英]Return object from array of objects

我有以下對象數組:

const values = [
    {
      clientType: "Client Type 1",
      value: 130
    },
    {
      clientType: "Client Type 2",
      value: 10
    },
    {
      clientType: "Client Type 3",
      value: -80
    },
    {
      clientType: "Client Type 4",
      value: -52
    }
  ]

我想“映射”這個數組並得到以下對象:

results = {
  "Client Type 1": 130,
  "Client Type 2": 10,
  "Client Type 3": -80,
  "Client Type 4": -52,
}

有沒有辦法直接做到這一點? (僅使用一個 map 功能)

TIA

 const values = [ { clientType: "Client Type 1", value: 130 }, { clientType: "Client Type 2", value: 10 }, { clientType: "Client Type 3", value: -80 }, { clientType: "Client Type 4", value: -52 } ] const result = values.reduce((acc, {clientType, value}) => ({...acc, [clientType]: value}), {}) console.log(result)

這段代碼似乎工作:

 const values = [ { clientType: "Client Type 1", value: 130 }, { clientType: "Client Type 2", value: 10 }, { clientType: "Client Type 3", value: -80 }, { clientType: "Client Type 4", value: -52 } ] values.map(getFull); function getFull(item) { return [item.clientType,item.value].join(" "); }

這是一個相當簡單的問題/任務,所以我將嘗試發布一個簡單易懂的答案。

 const values = [{ clientType: "Client Type 1", value: 130 }, { clientType: "Client Type 2", value: 10 }, { clientType: "Client Type 3", value: -80 }, { clientType: "Client Type 4", value: -52 } ], // loop through "values" object and construct and object the way the OP needs then return it. resultObj = values.reduce((a, c) => { // a: is the object that we are constructing, its default value is {} (empty object) // c: is the current object from the "values" array a[c.clientType] = c.value; return a; }, {}); // this line is not needed, it just prints the result to the console console.log(resultObj);

只是一個旁注(但相當重要),訪問結果 Object 上的屬性的唯一方法是使用括號表示法: resultObj['Client Type 1'] // prints: 130

在 MDN 上了解有關reduce方法的更多信息。

我希望你能試試這個代碼我希望它對你有用


const values = [
  {
    clientType: "Client Type 1",
    value: 130,
  },
  {
    clientType: "Client Type 2",
    value: 10,
  },
  {
    clientType: "Client Type 3",
    value: -80,
  },
  {
    clientType: "Client Type 4",
    value: -52,
  },
];

const results = {};
for (let i = 0; i < values.length; i++) {
  results[values[i].clientType] = values[i].value;
}

console.log("values", values);
// values [
//     { clientType: 'Client Type 1', value: 130 },
//     { clientType: 'Client Type 2', value: 10 },
//     { clientType: 'Client Type 3', value: -80 },
//     { clientType: 'Client Type 4', value: -52 }
//   ]

console.log("results", results);
//   results {
//     'Client Type 1': 130,
//     'Client Type 2': 10,
//     'Client Type 3': -80,
//     'Client Type 4': -52
//   }


暫無
暫無

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

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