我需要这种格式:
{ 0: 'apples', 1: 'oranges', 2: 'lemons' }
我曾经有一个没有键的数组,但是在应用Object.assign
之后,我目前有这种格式:
{ 0: {code: "apples"}, 1: {code: "oranges"}, 2: {code: "lemons"} }
对于将其转换为第一种格式的任何建议,我将不胜感激。
答案 0 :(得分:1)
您需要通过取出code
重新组合对象。
此方法使用(即将使用)Object.fromEntries
。
var object = { 0: { code: "apples" }, 1: { code: "oranges" }, 2: { code: "lemons" } },
result = Object.fromEntries(Object.entries(object).map(([key, { code }]) => [key, code]));
console.log(result);
答案 1 :(得分:0)
尝试
const data = { 0: 'apples', 1: 'oranges', 2: 'lemons' }
const result = Object.keys(data).reduce((acc, ele, i)=>({...acc, [i]: {code: data[i]}}), {});
console.log(result);
答案 2 :(得分:0)
let o = { 0: {code: "apples"}, 1: {code: "oranges"}, 2: {code: "lemons"} };
let oNew = {};
for (let prop in o) {
oNew[prop] = o[prop].code;
}
console.log(oNew);
答案 3 :(得分:-1)
使用array
从object
到reduce
:
console.log(['apples', 'oranges', 'lemons' ].reduce((p,c,i)=>({...p, [i]:c}), {}))