按对象键

时间:2018-05-10 10:00:33

标签: javascript arrays dictionary object ecmascript-6

考虑以下对象数组

const data = [{
    name: 'James',
    sex: 'male',
  }, {
    name: 'Mike',
    sex: 'male',
  }, {
    name: 'Janet',
    sex: 'female',
  }, {
    name: 'Mary',
    sex: 'female',
}];

我想退回以下内容:

{
  males: [{
    name: 'James',
    sex: 'male',
  }, {
    name: 'Mike',
    sex: 'male',
  }]
  females: [{
    name: 'Janet',
    sex: 'female',
  }, {
    name: 'Mary',
    sex: 'female',
}]
}

我尝试在数组上进行映射,按键选择对象,然后将它们添加到新数组中,结果是两个数组。从那里开始,我不知道如何以简洁的方式将它们归还新物体。

我不太熟悉ES6中的数组过滤/减少方法,它们在这里有用吗?任何帮助表示赞赏!

4 个答案:

答案 0 :(得分:1)

您可以使用reduce



const data = [{
  name: 'James',
  sex: 'male',
}, {
  name: 'Mike',
  sex: 'male',
}, {
  name: 'Janet',
  sex: 'female',
}, {
  name: 'Mary',
  sex: 'female',
}];

const result = data.reduce((c, v) => {
  c[v.sex] = c[v.sex] || [];       //Initiate if key does not exist
  c[v.sex].push(v);                //Push the value
  return c;
}, {});

console.log(result);




如果您希望密钥为复数,则只需附加'

const result = data.reduce((c, v) => {
  let k = v.sex + 's';
  c[k] = c[k] || [];           //Initiate if key does not exist
  c[k].push(v);                //Push the value
  return c;
}, {});

答案 1 :(得分:1)

尝试以下



const data = [{name:'James',sex:'male',},{name:'Mike',sex:'male',},{name:'Janet',sex:'female',},{name:'Mary',sex:'female',}];

var result = data.reduce((acc, obj) => {
  acc[obj.sex + "s"] = acc[obj.sex + "s"] || []; 
  acc[obj.sex + "s"].push(obj);
  return acc;
}, {});
console.log(result);




答案 2 :(得分:1)

简单的旧js简单 -

const data = [{
    name: 'James',
    sex: 'male',
  }, {
    name: 'Mike',
    sex: 'male',
  }, {
    name: 'Janet',
    sex: 'female',
  }, {
    name: 'Mary',
    sex: 'female',
}];

var result = { males: [], females: []};
data.forEach(function(person){
  person.sex === 'male' ? result.males.push(person) : result.females.push(person);
});

console.log(result);

答案 3 :(得分:1)

你可以这样做:

const data = [{name: 'James',sex: 'male'}, {name: 'Mike',sex: 'male'}, {name: 'Janet',sex: 'female'}, {name: 'Mary',sex: 'female'}];
const result = data.reduce((a, c) => (a[c.sex + 's'].push(c), a), {males: [], females: []});

console.log(result);