0

Im trying to group an array of objects by a value of one of the child objects.

Im kinda getting want I want using reduce, but it seems to be combining the group by value where the parent objects are common.

let name = [
  {
    issue: "89",
    status: ["test", "prod", "dev"]
  },
  {
    issue: "45",
    status: ["dev"]
  }
];

const groups = name.reduce((groups, item) => {
  const group = groups[item.status] || [];
  group.push(item);
  groups[item.status] = group;
  return groups;
}, {});

console.log(JSON. stringify(groups));

I get the below results

{
   "test,prod,dev":[
      {
         "issue":"89",
         "status":[
            "test",
            "prod",
            "dev"
         ]
      }
   ],
   "dev":[
      {
         "issue":"45",
         "status":[
            "dev"
         ]
      }
   ]
}

What id like is for it the produce the below:

{
   "prod":[
      {
         "issue":"89",
         "status":[
            "test",
            "prod",
            "dev"
         ]
      }
   ],
   "test":[
      {
         "issue":"89",
         "status":[
            "test",
            "prod",
            "dev"
         ]
      }
   ],
   "dev":[
      {
         "issue":"45",
         "status":[
            "dev"
         ]
      },
      {
         "issue":"89",
         "status":[
            "test",
            "prod",
            "dev"
         ]
      }
   ]
}

Im not sure how to produce my desired results easily.

many thanks

2 Answers 2

1

You need to group your object based on the status. You can use array#reduce with array#forEach.

const names = [ { issue: "89", status: ["test", "prod", "dev"] }, { issue: "45", status: ["dev"] } ],
      result = names.reduce((r, o) => {
        o.status.forEach(name => {
          r[name] ??= [];
          r[name].push(JSON.parse(JSON.stringify(o)));
        });
        return r;
      },{});
console.log(result);

Sign up to request clarification or add additional context in comments.

2 Comments

This works perfectly in the sandbox environment but when I try to run it locally i get the error r[name] ??= []; SyntaxError: Unexpected token '?' Do i have something locally not setup corrrectly?
Just replace that line with r[name] = r[name] || []
1
const group = Object.assign({}, ...name.reduce((p, c) => [...p, ...c.status], [])
.filter((v, i , a) => a.indexOf(v) === i)
.map(item => ({ [item]: name.filter(old => old.status.includes(item)) })))

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.