Reputation: 6846
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
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
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
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
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