【问题标题】:Convert an array of ojects to an object将对象数组转换为对象
【发布时间】:2019-07-11 12:51:45
【问题描述】:

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

我的代码

 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, …}

【问题讨论】:

  • 给出真实代码而不是从控制台复制
  • 期望每个对象都有相同的键集。在这种情况下,您无法将其转换为 object,因为对象不能有重复键
  • 您的情况有什么独特之处?因为对象应该有唯一的键
  • 什么是data.questions?
  • Convert Array to Object的可能重复

标签: javascript arrays angularjs angular object


【解决方案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]);

【讨论】:

  • @数组中有多个对象怎么样?
  • @JanMichaelDough - 提供你想要的输入和输出。
  • 数据 (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)
  • 输出在哪里?
  • 这是我想把它分成两个对象的捕获
【解决方案2】:

您可以使用Object.assign()

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

【讨论】:

  • 它在这里工作。不知道什么不适合你。如果您愿意详细说明?
猜你喜欢
  • 2020-06-15
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
相关资源
最近更新 更多