Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract and append objects from an array of objects in JS

The question is pretty straight forward. I feel dumb asking this because I'm sure the answer is right in front of me, but anyways here is the question.

I'm given a response data and the JSON is sort of like this:

$scope.testData = [
        {
            food: 'wet',
            animal: [{name: 'cat', value: '1'},
                    {name: 'dog', value: '2'}]
        },
        {
            food: 'dry',
            animal: [{name: 'bird', value: '3'},
                    {name: 'fish', value: '4'}]
        }
    ];

The question at hand is how can I pull the nested objects under animal so I can set a string up and and push it with the current food object for example:

I would take out the animal: names so under object with food: 'wet' I would take out animal:

[{name: 'cat', value: '1'},
 {name: 'dog', value: '2'}]

Then I would take the object names 'cat' and 'dog' put into a string like cat, dog and then push the new values into a new array of objects that look like this

$scope.newData = [
        {
            food: 'wet',
            animalType: 'cat, dog'
        },
        {
            food: 'dry',
            animalType: 'bird, fish'
        }
    ];

This is all done so I can have a cleaner UI grid

like image 630
McMintz Avatar asked Dec 14 '25 21:12

McMintz


1 Answers

It's really great that you've already broken the problem down into steps, now we just need to understand the tools we can use to turn those steps into code!

First, we are going to want to run the same operation over every time in this collection and return a brand new collection. This is called map.

We can map over our data by writing:

data.map((item) => { .. });

This will return a brand new collection where each item is the result of passing the item in data to the function given to map.

Next, we want to take our animal collection and convert it from a collection to a new collection using map, then join that new collection into a single value, a string.

We can do this to our animal by writing:

animal.map((item) => { .. }).join(', ');

This will return a single string, joined with whatever you give to join.

Let's take a look at the final code, below.

const data = [
  {
    food: 'wet',
    animal: [
      {
        name: 'cat',
        value: '1'
      },
      {
        name: 'dog',
        value: '2'
      }
    ]
  },
  {
    food: 'dry',
    animal: [
      {
        name: 'bird',
        value: '3'
      },
      {
        name: 'fish',
        value: '4'
      }
    ]
  }
];

const finalData = data.map((item) => {
  return {
    food: item.food,
    animalType: item.animal.map((item) => {
      return item.name;
    }).join(', ')
  };
});
like image 113
vanev_ Avatar answered Dec 16 '25 14:12

vanev_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!