0

Suppose I have a series of arrays like this:

[{title: 'foo', data: 'something here'}, 
 {title: 'foo', data: 'something else here'}, 
 {title: 'bar', data: 'something else again'}
]

What would be nice is if I could transform them into a series of objects grouped by title as the key.

So the transformation would look something like this:

{
    'foo': {data: ['something else', 'something else here']}
    'bar': {data: ['something else again']}
}

How would I go about that in a somewhat elegant manner?

2 Answers 2

3

What you're looking for is the reduce function.

let myArray = [
  {title: 'foo', data: 'something here'}, 
  {title: 'foo', data: 'something else here'}, 
  {title: 'bar', data: 'something else again'}
];


myArray = myArray.reduce((obj, value) => {

  // Check to see if the "Title" exists in the object
  if (!obj[value.title]) {

    // If not, create it
    // and initialize "data" as an empty array
    obj[value.title] = {
      data: []
    };
  }

  // Push data to the data array in our object
  obj[value.title].data.push(value.data);

  return obj;

}, {});
Sign up to request clarification or add additional context in comments.

Comments

1

You can apply reduce,filter and map

let arr=[{title: 'foo', data: 'something here'}, 
 {title: 'foo', data: 'something else here'}, 
 {title: 'bar', data: 'something else again'}
]
const convert_to_object = (myarray) =>
   myarray.reduce((o, i) => {
     o[i.title] = {data:myarray.filter(m=>m.title==i.title).map(m=>m.data)}
     return o
   }, {})
const someobj = convert_to_object(arr)
console.log(someobj)

2 Comments

Your JavaScript kung-fu is strong my friend, but I'm marking the other person correct because he doesn't have your high rep. :) You still get the upvote.
FYI this solution is O(n^2) rather than the solution I provided above which is O(n). Would advise actually not using nested loops like this

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.