在一个数组中过滤多个键值(obvjects的数组)

Filter multiple key values(Array of an obvjects) in one array

提问人:Siva Sai 提问时间:11/7/2023 更新时间:11/7/2023 访问量:22

问:

我有一个键值对格式,我想将数组中的所有值过滤到一个数组中

const holiday_expenses = {
  food: [{name: "abc", place: "xyz"}],
  travel: [{name: "abcd", place: "xyz1"}],
  accommodation: [{name: "xysz", place: "xyz2"}]
}

预期成果:

result : [{name: "abc", place: "xyz"}, {name: "abcd", place: "xyz1"}, {name: "xysz", place: "xyz2"}]
javascript reactjs angularjs 键值

评论


答:

0赞 Robby Cornelissen 11/7/2023 #1

只需获取对象的所有并将它们展平:

const result = Object.values(holiday_expenses).flat();

完整片段:

const holiday_expenses = {
  food: [{name: "abc", place: "xyz"}],
  travel: [{name: "abcd", place: "xyz1"}],
  accommodation: [{name: "xysz", place: "xyz2"}]
};

const result = Object.values(holiday_expenses).flat();

console.log(result);

0赞 Chenxiang Wang 11/7/2023 #2

import "_" from lodash;
cosnt obj = {/...whatever you have/}
const res = _.values(obj);

勾选“lodash”,相信它能让你生活得更美好。https://lodash.com/docs/有许多辅助函数可以操作数组和对象。