将对象的对象转换为单个对象

时间:2019-06-27 11:18:08

标签: javascript object

我需要这种格式:

{ 0: 'apples', 1: 'oranges', 2: 'lemons' }

我曾经有一个没有键的数组,但是在应用Object.assign之后,我目前有这种格式:

{ 0: {code: "apples"}, 1: {code: "oranges"}, 2: {code: "lemons"} }

对于将其转换为第一种格式的任何建议,我将不胜感激。

4 个答案:

答案 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)

使用arrayobjectreduce

console.log(['apples', 'oranges',  'lemons' ].reduce((p,c,i)=>({...p, [i]:c}), {}))