簡體   English   中英

使用數組中的鍵值對創建 object

[英]Create an object with key-value pairs from an array

有這個輸入數組:

const myArray = [{value: "test"}, {value: "abc"}, {value: "xyz"}];

期望的結果是這樣的: result = { "value1": "test", "value2": "abc", "value3": "xyz" };

我試過這樣做,但它返回一個空的 object: {undefined: ""}

const result = myArray.reduce((agg, item) => {
  agg[item.key] = item.value;
  return agg;
}, {})

有任何想法嗎?

您可以使用Object.keys讀取鍵的名稱,並使用array.reduce的第三個參數獲取當前處理的項目的索引。

 const myArray = [{value: "test"}, {value: "abc"}, {value: "xyz"}]; //the desired result is this: result = { "value1": "test", "value2": "abc", "value3": "xyz" }; const result = myArray.reduce((agg, item, index) => { agg[Object.keys(item)[0] + (index + 1)] = item.value; return agg; }, {}) console.log(result);

你可以試試,

 const myArray = [{value: "test"}, {value: "abc"}, {value: "xyz"}]; const result = myArray.reduce((agg, item, index) => { // append the array index to the key "value" agg[Object.keys(item)[0] + (index + 1)] = item[Object.keys(item)[0]]; return agg; }, {}); console.log(result);

上面的代碼會將值動態分配給“對象”的新索引鍵

暫無
暫無

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

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