2

I'm trying to figure out how I would parse the following information:

{
  'unknown-value': {
    name: 'AB',
    id: 'BLUE'
  },
  'unknown-value': {
    name: 'AC',
    id: 'PURPLE'
  }
}

Wanting to parse them then create an array of values like these:

names = ['AB', 'AC']
ids = ['BLUE', 'PURPLE']

Haven't come across something like this where it isn't an array of objects so I'm a little stumped on what to do.

1
  • 4
    have you tried Object.values? Commented Dec 25, 2020 at 13:22

4 Answers 4

2
  • You can iterate through your array of objects with forEach
  • Then get the values of the object with Object.values().
  • You can go then with forEach over these values and push it into the dedicated array names or ids in this case.

   
const obj = [{
  'unknown-value': {
    name: 'AB',
    id: 'BLUE'
  },
  'unknown-value2': {
    name: 'AC',
    id: 'PURPLE'
  }
}]

let names = [];
let ids = [];

obj.forEach((x) => { 
Object.values(x).forEach((y)=>{
  names.push(y.name);
  ids.push(y.id);
 })
})

console.log(names);
console.log(ids);

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

Comments

1

You might need that unknown key as well, so Object.entries is your friend:

const normalized = Object.entries(obj).map(([key, value]) => ({key, ...value}));

Now normalized contains an array of objects each with a new property "key" which contains the key.

Comments

1

const { names, ids, } = Object.values({

  'foo': {
    name: 'AB',
    id: 'BLUE',
  },
  'bar': {
    name: 'AC',
    id: 'PURPLE',
  }
}).reduce((map, item) => {

  map.names.push(item.name)
  map.ids.push(item.id)

  return map;

}, { names: [], ids: [] });

console.log('names :', names);
console.log('ids :', ids);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Comments

0

As simple as it can get, try this approach and you will find the desired result

object = {
  'unknown-value': {
    name: 'AB',
    id: 'BLUE'
  },
  'unknown-value': {
    name: 'AC',
    id: 'PURPLE'
  }
};

names = [];
ids = [];

for (key in object) {
    names.push(object[key].name);
    ids.push(object[key].id);        
}

for (value of names) {
    console.log(value);
}

for (value of ids) {
    console.log(value);
}

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.