gpt4 book ai didi

javascript - 在对象数组中查找值

转载 作者:行者123 更新时间:2023-12-05 01:50:07 27 4
gpt4 key购买 nike

  const objectTest = {
Shoes: [
{ id: 1, name: "xxx", image: "xxxxxx" },
{ id: 2, name: "yyy", image: "yyyyyy" },
],
Top: [
{ id: 1, name: "zzz", image: "zzzzzz" },
{ id: 2, name: "aaa", image: "aaaaaa" },
],
};

我知道我可以使用查找方法。

 const item = objectTest.Shoes.find((p) => p.name === "xxx");
console.log(item); ///{id: 1, name: 'xxx', image: 'xxxxxx'}

但是如果我不知道“xxx”属于 Shoes 组怎么办。如何找到 "xxx" 并返回 { id: 1, name: "xxx", image: "xxxxxx"}

最佳答案

最简单的方法是先展平对象值:

Object.values(objectTest).flat()

然后就可以正常找到了:

const item = Object.values(objectTest).flat().find((p) => p.name === "xxx");

如果你想知道它属于哪个“组”,你必须遍历Object.entries(objectTest)

关于javascript - 在对象数组中查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73397573/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com