将对象数组减少为对象

时间:2017-03-24 20:03:41

标签: javascript arrays ecmascript-6

我有以下数组

data = [
  { name: 'foo', type: 'fizz', val: 9 },
  { name: 'boo', type: 'buzz', val: 3 },
  { name: 'bar', type: 'fizz', val: 4 },
  { name: 'car', type: 'buzz', val: 7 },
];

如何制作

{
    9: 'foo',
    3: 'boo,
    4: 'bar',
    7: 'car'
}
ES6中的

提前致谢!!

3 个答案:

答案 0 :(得分:4)

使用Array#forEach



var data = [ { name: 'foo', type: 'fizz', val: 9 }, { name: 'boo', type: 'buzz', val: 3 }, { name: 'bar', type: 'fizz', val: 4 }, { name: 'car', type: 'buzz', val: 7 }, ], 
    res = {};
    data.forEach(v => res[v.val] = v.name);

    console.log(res);




使用Array#reduce



var data = [ { name: 'foo', type: 'fizz', val: 9 }, { name: 'boo', type: 'buzz', val: 3 }, { name: 'bar', type: 'fizz', val: 4 }, { name: 'car', type: 'buzz', val: 7 }, ],
    res = data.reduce(function(s,a){
      s[a.val] = a.name;
      return s;
    }, {});
  
    console.log(res);




答案 1 :(得分:1)

这样的事情应该有效:



const data = [
  { name: 'foo', type: 'fizz', val: 9 },
  { name: 'boo', type: 'buzz', val: 3 },
  { name: 'bar', type: 'fizz', val: 4 },
  { name: 'car', type: 'buzz', val: 7 },
];

const reduced = data.reduce((acc, item) => {
  acc[item.val] = item.name;
  return acc;
}, {});

console.log(reduced);




答案 2 :(得分:1)

您可以使用Object.assign并使用生成的computed property names和值映射对象。



var data = [{ name: 'foo', type: 'fizz', val: 9 }, { name: 'boo', type: 'buzz', val: 3 }, { name: 'bar', type: 'fizz', val: 4 }, { name: 'car', type: 'buzz', val: 7 }],
    object = Object.assign({}, ...data.map(o => ({ [o.val]: o.name })));

console.log(object);

.as-console-wrapper { max-height: 100% !important; top: 0; }