JorahFriendzone
JorahFriendzone

Reputation: 433

How to add to an array within an object

I have this object and I'm trying to convert it.

names = {
  animals: ['Dog', 'Cat', 'Snake'],
  flowers: ['Rose', 'Daisy']
}

I want to convert it into something like this

newObject = {
  type: ['animals', 'flowers']
  subtype: ['Dog', 'Cat', 'Snake', 'Rose', 'Daisy']
}

I wrote the following function but for some reason it's not populating correctly.

const newObject = {};

Object.keys(names).map(type => {
  newObject['types'] = [...newObject['types'], type];
      names[type].map(subtype => {
        newObject['subtypes'] = [...newObject['subtypes'], subtype];
      })
    })

Upvotes: 0

Views: 63

Answers (4)

Nick Parsons
Nick Parsons

Reputation: 50954

Your .map() callback should return what you want each element to turn into, so the callback behaves somewhat like a transformation function. However, for a case like this, you don't need to use .map() and can just extract the keys and values from the object. As your values are arrays, you can use .flat() to merge the array of arrays into the one larger array of values for your subtype key:

const names = {
  animals: ['Dog', 'Cat', 'Snake'],
  flowers: ['Rose', 'Daisy']
}

const type = Object.keys(names);
const subtype = Object.values(names).flat();

const newObject = {type, subtype};
console.log(newObject);

Upvotes: 5

Omer
Omer

Reputation: 3496

Global solution for any keys and values

use Object.keys and Object.values with array.reduce() :)

const names = {
   animals: ['Dog', 'Cat', 'Snake'],
   flowers: ['Rose', 'Daisy']
}

const newObject = {
   type: Object.keys(names),
   subtype: Object.values(names).reduce((acc, item)=> [...acc, ...item],[])
}

console.log(newObject);

Upvotes: 0

blex
blex

Reputation: 25648

You can also use reduce to build a new object:

const names = {
  animals: ['Dog', 'Cat', 'Snake'],
  flowers: ['Rose', 'Daisy']
};

const res = Object.entries(names)
                  .reduce(
                    ({type, subtype}, [key, values]) => ({
                      type: type.concat(key),
                      subtype: subtype.concat(values)
                    }),
                    { type: [], subtype: [] } // Starting value
                  );

console.log(res);

Upvotes: 0

Edoardo Pacciani
Edoardo Pacciani

Reputation: 209

newObject = {
  type: ['animals', 'flowers']
  subtype: [...names.animals, ...names.flowers] 
}

Upvotes: 0

Related Questions