我如何找到任何项目在一个数组内的对象



我有这个数据

{playstation: Array(1), freefire: Array(1), pubg: Array(1), roblox: Array(1), steam: Array(1), …}

数组是这样的:

freefire: [{…}]
playstation: [{…}]
pubg: [{…}]
razorgold: [{…}]
roblox: [{…}]
steam: [{…}]
{
"freefire": {
"id": 1,
"attributes": {
"ProductCode": "427",
"createdAt": "2022-06-09T11:29:04.187Z",
"updatedAt": "2022-06-09T11:29:05.518Z",
"publishedAt": "2022-06-09T11:29:05.513Z",
"ProductCodeAlt": "FLASH-427",
"Name": "20",
"FaceValue": 20,
"DefaultCost": 2000,
"Description": "R20 Uber Token",
"Vendor": "Uber",
"VendorId": 15,
}
}
}

我正在尝试用这种方法在数据中找到任何东西。

const item = data.freefire.find(
(item) => String(item.ProductCode) === ProductCode
);

它只在指定项路径时起作用。我不想详细说明。我只是想这样做。

const item = data.find(
(item) => String(item.ProductCode) === ProductCode
);

但似乎不工作

那么,看看下面的代码

const data = {
first: [
{
ProductCode: 1,
otherStuff: "other stuff A"
},
{
ProductCode: 1,
otherStuff: "other stuff B"
},
{
ProductCode: 2,
otherStuff: "other stuff X1"
},
],
second: [
{
ProductCode: 1,
otherStuff: "other stuff C"
},
{
ProductCode: 3,
otherStuff: "other stuff X2"
},
{
ProductCode: 2,
otherStuff: "other stuff X3"
},
]
}
const ProductCode = 1;
const result = Object.keys(data).map(key => data[key].filter(item => item.ProductCode === ProductCode)).flat(1);
console.log(result);

这将记录

[
{
"ProductCode": 1,
"otherStuff": "other stuff A"
},
{
"ProductCode": 1,
"otherStuff": "other stuff B"
},
{
"ProductCode": 1,
"otherStuff": "other stuff C"
}
]

编辑

通过改变对象的结构对答案进行了编辑,这里的原则仍然是一样的。

如果您正在寻找单个搜索命中,您可以查看主对象的每个键,进入其数组并搜索,最后返回您的查找。

const codeToFind = 3;
const data = {
playstation: [{ productCode: 1 }],
freefire: [{ productCode: 2 }],
pubg: [{ productCode: 3 }],
roblox: [{ productCode: 4 }],
steam: [{ productCode: 5 }],
};

let found;
const result = Object.keys(data).find((key) => data[key].find((subObject) => subObject.productCode === codeToFind));

最新更新