Edgar
Edgar

Reputation: 6846

How to make an array of multiple nested objects?

I have such an object.

let Filus = {
     male: {
    hat: [1],
    jacket: [2],
    pants: [3],
    shoes: [4],
    suit: [5]
  }
};

I want to get this array from this object.

let Filus = [1,2,3,4,5];

How to do it?

Upvotes: 3

Views: 1071

Answers (4)

Slai
Slai

Reputation: 22866

If the object is from a JSON string, the numbers can be extracted during parsing :

var arr = [], json = '{"male":{"hat":[1],"jacket":[2],"pants":[3],"shoes":[4],"suit":[5]}}'

JSON.parse(json, (k, v) => v.toFixed && arr.push(v))

console.log(arr)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

You could take a Generator and return all found values of the object and it's nested objects.

This approach relies on language inherent order of objects.

function* values(o) {
    if (o && typeof o === 'object') for (let v of Object.values(o)) yield* values(v);
    else yield o;
} 

let filus = { male: { hat: [1], jacket: [2], pants: [3], shoes: [4], suit: [5] } },
    result = [...values(filus)];

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36564

You can get values of nested object male using Object.values() and then use flat()

let Filus = { male : { hat: [1], jacket: [2], pants: [3], shoes: [4], suit: [5] } };

const res = Object.values(Filus.male).flat();
console.log(res)

You can also do that without flat() using concat() and spread operator.

let Filus = { male : { hat: [1], jacket: [2], pants: [3], shoes: [4], suit: [5] } };

const res = [].concat(...Object.values(Filus.male));
console.log(res)

Upvotes: 5

Jack Bashford
Jack Bashford

Reputation: 44087

Just use Object.values and flat - this works even if you don't know the key of the nested object:

let Filus = {
  male: {
    hat: [1],
    jacket: [2],
    pants: [3],
    shoes: [4],
    suit: [5]
  }
};

const res = Object.values(Object.values(Filus)[0]).flat();
console.log(res);

ES5 syntax:

var Filus = {
  male: {
    hat: [1],
    jacket: [2],
    pants: [3],
    shoes: [4],
    suit: [5]
  }
};

var res = Object.keys(Filus[Object.keys(Filus)[0]]).map(function(key) { 
  return Filus[Object.keys(Filus)[0]][key];
}).reduce(function(acc, curr) {
  return acc.concat(curr);
});

console.log(res);


It's also easy if you have the key:

let Filus = {
  male: {
    hat: [1],
    jacket: [2],
    pants: [3],
    shoes: [4],
    suit: [5]
  }
};

const res = Object.values(Filus.male).flat();
console.log(res);

ES5 syntax:

var Filus = {
  male: {
    hat: [1],
    jacket: [2],
    pants: [3],
    shoes: [4],
    suit: [5]
  }
};

var res = Object.keys(Filus.male).map(function(key) { 
  return Filus.male[key];
}).reduce(function(acc, curr) {
  return acc.concat(curr);
});

console.log(res);

Upvotes: 4

Related Questions