logan brunner
logan brunner

Reputation: 21

JavaScript: For each object in object?

I have an object that looks like this:

{
 object1: {
            version: 1.0.0,
            name: Name1
          },
 object2: {
            version: 1.0.0,
            name: Name2
          },
 object3: {
            version: 1.0.0,
            name: Name3
          }
}

I need to make an array with each objects name. How can i loop over this object and get each objects name?

Upvotes: 2

Views: 1656

Answers (4)

Ande Caleb
Ande Caleb

Reputation: 1204

i hope this works...

             let obj = {
                object1: {
                            version: "1.0.0",
                            name: "Name1"
                        },
                object2: {
                            version: "1.0.0",
                            name: "Name2"
                        },
                object3: {
                            version: "1.0.0",
                            name: "Name3"
                        }
                };


            let array = Object.values(obj); //push values to new array without keys                
            let Names = []; //Empty Names array... 

            array.map(o => {
                Names.push(o.name);  //loop and push the names to new array
            });

            console.log(Names); //array of names;

Upvotes: 0

dayfine
dayfine

Reputation: 27

https://github.com/airbnb/javascript#iterators-and-generators

Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like for-in or for-of. eslint: no-iterator no-restricted-syntax

Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.

Use ... Object.keys() / Object.values() / Object.entries() to produce arrays so you can iterate over objects.

So:

const names1 = Object.values(obj).map((sub_obj) => sub_obj.name)
const names2 = Object.keys(obj).map((key) => obj[key].name)

Upvotes: 1

thammada.ts
thammada.ts

Reputation: 5245

If you don't need IE support there is a functional approach: Object.entries()

const obj = {
 object1: {
            version: 1.0.0,
            name: Name1
          },
 object2: {
            version: 1.0.0,
            name: Name2
          },
 object3: {
            version: 1.0.0,
            name: Name3
          }
}

const names = Object.entries(obj).map(([key, value]) => value.name)

Upvotes: 0

Ilijanovic
Ilijanovic

Reputation: 14914

with the for... in loop:

let obj = {
       object1: {
            version: "1.0.0",
            name: "Name1"
          },
       object2: {
            version: "1.0.0",
            name: "Name2"
          },
       object3: {
            version: "1.0.0",
            name: "Name3"
          }
    }

    for(let key in obj){
       name = obj[key].name;
       console.log(name);
    }

Upvotes: 2

Related Questions