0

From a service call, I receive similar JSON data like follows:

myArray: any = [
{item: 'Jelly Beans', areaCode: 321, Company: "Bob's Candy"},
{item: 'Skittles', areaCode: 444, Company: "Jim's Candy"},
{item: 'Snickers', areaCode: 321, Company: "Bob's Candy"},
{item: 'M&Ms', areaCode: 444, Company: "Jim's Candy"},
{item: 'Gummy Bears', areaCode: 123, Company: "Sally's Candy"}];

I need to split this into multiple arrays of objects dynamically, based on areaCode.

Or create a new object dynamically based on areaCode.

this.myArray= this.data.map(item => item.areaCode)
.filter((value, index, self) => self.indexOf(value) === index);

I have thoughts of using the map function and filtering it out based on the areaCode, and then perhaps creating a new object with arrays based on areaCode. I just cannot seem to wrap my head around the process. If anyone could offer some advice I would be grateful.

1
  • 3
    What is the expected output? Commented Mar 6, 2019 at 5:04

2 Answers 2

1

you are expecting something like this as output

{
"123":[{"item":"Gummy Bears","areaCode":123,"Company":"Sally's Candy"}],
  "321":[{"item":"Jelly Beans","areaCode":321,"Company":"Bob's Candy"}, 
         {"item":"Snickers","areaCode":321,"Company":"Bob's Candy"}],
  "444":[{"item":"Skittles","areaCode":444,"Company":"Jim's Candy"}, 
         {"item":"M&Ms","areaCode":444,"Company":"Jim's Candy"}]
}

then you can reduce to achieve it

const output = myArray.reduce((res,v) => {
    if(!res[v.areaCode]) {
        res[v.areaCode] = [v] 
    } else {
    res[v.areaCode].push(v)
    }
return res
},{} )
Sign up to request clarification or add additional context in comments.

Comments

1

You can instead use .reduce to convert your array to an object, and then use Object.values() to get your array of unique objects from the reduces object like so:

const arr = [
{item: 'Jelly Beans', areaCode: 321, Company: "Bob's Candy"},
{item: 'Skittles', areaCode: 444, Company: "Jim's Candy"},
{item: 'Snickers', areaCode: 321, Company: "Bob's Candy"},
{item: 'M&Ms', areaCode: 444, Company: "Jim's Candy"},
{item: 'Gummy Bears', areaCode: 123, Company: "Sally's Candy"}];

const res = Object.values(arr.reduce((acc, {item, areaCode, Company}) => {
  if(areaCode in acc) {
    acc[areaCode].item.push(item);
  } else {
    acc[areaCode] = {item: [item], areaCode, Company};
  };
  
  return acc;
}, {}));

console.log(res);

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.