我想要实现的是将对象数组转换为对象。
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, …}
答案 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)