使用数组中的键值对创建对象

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" };

我试过了,但它 returns 是一个空对象:{undefined: ""}

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

有什么想法吗?

您可以使用Object.keys to read the name of the key and use the 3rd parameter of 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);

以上代码会将值动态分配给 'objects' 个新索引键