0

Hi i'm having an object like [{name: 'abc', country : 'US'},{name: 'xyz', country : 'IN'},{name: 'mno', country : 'US'},{name: 'pqr', country : 'IN'}]

I need to convert object above into

{ US : [abc,mno], IN: [xyz,pqr] } using angular js. can anyone help me to achive this.

1
  • Check out Array.reduce(). Commented Jul 15, 2020 at 14:58

1 Answer 1

2

Use Array.reduce() to convert the array of objects into a object derived from the array data.

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

The variable output results in -

{
  "US": [
    "abc",
    "mno"
  ],
  "IN": [
    "xyz",
    "pqr"
  ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.