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.

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
  • 4
    have you tried [`Object.values`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values)? – Nina Scholz Dec 25 '20 at 13:22

4 Answers4

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);
Aalexander
  • 4,987
  • 3
  • 11
  • 34
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.

James
  • 20,957
  • 5
  • 26
  • 41
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; }
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
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);
}
Ayush
  • 457
  • 8
  • 16