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?
4 Answers 4
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)
Comments
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);
Comments
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; }
Comments
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)
Comments
Explore related questions
See similar questions with these tags.
ecmascript-6? Because it haslet?