将对象数组转换为对象

时间:2019-02-18 07:19:47

标签: javascript arrays angularjs angular object

我想要实现的是将对象数组转换为对象。

mycode

 var arr = data.questions
        var obj = {};
        for (let i = 0; i < arr.length; i++) {
            obj[arr[i].key] = arr[i].value;
        }
        console.log(obj)

结果

data 
(2) [{…}, {…}]
0: {id: 48, questionaire: 94, question: "Helloworld", input_answer: null, order: 0, …}
1: {id: 49, questionaire: 94, question: "sadasdas", input_answer: null, order: 1, …}
length: 2
__proto__: Array(0)

想要实现

questions {id: 11, questionaire: 16, question: "what?", input_answer: null, order: 0, …}

2 个答案:

答案 0 :(得分:1)

const input = [
    {id: 48, questionaire: 94, question: "Helloworld", input_answer: null, order: 0},
    {id: 49, questionaire: 94, question: "sadasdas", input_answer: null, order: 1}
];

const output = input.reduce((a, obj)=>{
    a[obj.id] = obj;
    return a;
}, {});

console.log(output);
// Or you can access the specific objects using there keys
console.log(output[48]);
console.log(output[49]);

如果数组中只有一个对象,则只需使用index访问该对象。

var array = [{id: 44, questionaire: 90, question: "asd", input_answer: null, order: 0}];

console.log(array[0]);

答案 1 :(得分:0)

您可以使用Object.assign()

var a = [{
  a: 1
}, {
  b: 2
}, {
  c: 3
}]
var obj = {};
a.forEach(e => {
  Object.assign(obj, e)
})
console.log(obj)