Javascript 在angular js中动态构造键和值为列表的对象

Javascript 在angular js中动态构造键和值为列表的对象,javascript,arrays,angularjs,Javascript,Arrays,Angularjs,嗨,我有一个像[{name:'abc',country:'US'},{name:'xyz',country:'IN'},{name:'mno',country:'US'},{name:'pqr',country:'IN'}的对象] 我需要将上面的对象转换为 {US:[abc,mno],IN:[xyz,pqr]}使用角度js。有谁能帮我做到这一点。使用Array.reduce()将对象数组转换为从数组数据派生的对象 const input = [ {name: 'abc', country

嗨,我有一个像[{name:'abc',country:'US'},{name:'xyz',country:'IN'},{name:'mno',country:'US'},{name:'pqr',country:'IN'}的对象]

我需要将上面的对象转换为

{US:[abc,mno],IN:[xyz,pqr]}使用角度js。有谁能帮我做到这一点。

使用
Array.reduce()
将对象数组转换为从数组数据派生的对象

const input = [
    {name: 'abc', country : 'US'},
    {name: 'xyz', country : 'IN'},
    {name: 'mno', country : 'US'},
    {name: 'pqr', country : 'IN'}
];

// use reduce to loop over each element and return a constructed object
const output = input.reduce(function(accumulator, element) {
  // check to see if there is an entry for this country
  if (!accumulator[element.country]) {
    // if not create a new array with just this name as the only entry
    accumulator[element.country] = [element.name];
  } else {
    // already exists, push the new value
    accumulator[element.country].push(element.name);
  }
  // return the object
  return accumulator;
}, {}); // <- initial value
使用
Array.reduce()
将对象数组转换为从数组数据派生的对象

const input = [
    {name: 'abc', country : 'US'},
    {name: 'xyz', country : 'IN'},
    {name: 'mno', country : 'US'},
    {name: 'pqr', country : 'IN'}
];

// use reduce to loop over each element and return a constructed object
const output = input.reduce(function(accumulator, element) {
  // check to see if there is an entry for this country
  if (!accumulator[element.country]) {
    // if not create a new array with just this name as the only entry
    accumulator[element.country] = [element.name];
  } else {
    // already exists, push the new value
    accumulator[element.country].push(element.name);
  }
  // return the object
  return accumulator;
}, {}); // <- initial value
签出Array.reduce()。签出Array.reduce()。