0

I tried to print "person[0].name: a" and "person[1].name: b" and so on, based on this person array of object:

I used object entries twice, any other way I can make the loop more efficient?

const person = [{
  name: 'a',
}, {
  name: 'b'
}]

Object.entries(person).forEach(([key, value]) => {
  Object.entries(value).forEach(([key2, value2]) => {
    console.log(`person[${key}].${key2}`, ':', value2)
  })
})

2
  • Is your aim to just print the values at the name key or transform your array into an array of names (eg: ['a', 'b'])? Commented Jul 10, 2020 at 11:28
  • do you have nested objects/arrays as well? Commented Jul 10, 2020 at 11:31

3 Answers 3

1

You could take a recursive approach and hand over the parent path.

const
    show = (object, parent) => {
        const wrap = Array.isArray(object) ? v => `[${v}]` : v => `.${v}`;
        Object.entries(object).forEach(([k, v]) => {
            if (v && typeof v === 'object') show(v, parent + wrap(k));
            else console.log(parent + wrap(k), v);
        });
    },
    person = [{ name: 'a' }, { name: 'b' }];

show(person, 'person');

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

Comments

0

You don't really need the first call. person is already an Array.

const person = [{
  name: 'a',
}, {
  name: 'b'
}]


person.forEach((value, key) => {
  Object.entries(value).forEach(([key2, value2]) => {
    console.log(`person[${key}].${key2}`, ':', value2)
  })
})

Just in case forEach is for side effects. If you want to create another array with transformed values you better use map/flatMap instead.

const person = [{
  name: 'a',
}, {
  name: 'b'
}]


const transformed = person.flatMap((value, key) => {
  return Object.entries(value).map(([key2, value2]) => `person[${key}].${key2}:${value2}`)
})

console.log(transformed)

Comments

0

You can also try something like this, with only one forEach() loop

const person = [{
    name: 'a',
  },{
      name: 'b'
  }];
  
  
person.forEach((el,i) => {
        let prop = Object.keys(el).toString();
        
        console.log(`person[${i}].${prop}`, ':', el[prop])  
});
        
          

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.