JavaScript入門 オブジェクトのすべての値を取得する

オブジェクトのすべての値を取得して配列で返したい場合
const input = {
name: 'tamiboz',
favorite: {
fruit: 'orange',
animal: {
name: 'flog',
color: 'green',
},
},
married: 'yes',
};
↓
["tamiboz", "orange", "flog", "green", "yes"]
以下のようなコードで実現できます。
const getAllValues = obj => {
return Object.values(obj).map(v => {
if(typeof v === 'string') return v
return getAllValues(v);
}).flat();
}
const input = {
name: 'tamiboz',
favorite: {
fruit: 'orange',
animal: {
name: 'flog',
color: 'green',
},
},
married: 'yes',
};
const result = getAllValues(input);
console.log(result);
オブジェクトの値はすべて文字列であることが前提です。
getAllValues 内の条件判定の部分を変更することでより柔軟に対応できると思います。
最近のコメント