gpt4 book ai didi

javascript - 按特定键的值在多个数组中查找对象

转载 作者:行者123 更新时间:2023-12-04 08:47:11 25 4
gpt4 key购买 nike

我需要通过 target 在多个数组中找到一个对象值并返回 source值(value)。
数据如下所示:

{
"something": [
{
"type": "static",
"source": "data-access-select",
"target": "data-access-graphql"
},
{
"type": "static",
"source": "return-me",
"target": "find-me"
}
],
"anything": [
{
"type": "static",
"source": "data-access-page-index",
"target": "data-access-graphql"
}
]
}
所以有多个数组。
const depsBuffer = await readFile(
resolve('node_modules/.cache/nx/nxdeps.json')
)
const deps = JSON.parse(depsBuffer.toString('utf-8')).dependencies

for (const [key, value] of Object.entries(deps)) {
const res = value.find(x => x.target === 'find-me').source
console.log(res); // expected: 'return-me'
}
但是这样我确实得到了 ts 错误 Property 'find' does not exist on type 'unknown'

最佳答案

报错的原因是TypeScript不知道value是一个数组。它看到 valueunknown .
尝试指定一种类型来描述 JSON 的预期形状

interface Dependencies {
[key: string]: Array<{
type: string,
source: string,
target: string
}>;
}

const depsBuffer = await readFile(
resolve('node_modules/.cache/nx/nxdeps.json')
);
const deps = JSON.parse(depsBuffer.toString('utf-8')).dependencies as Dependencies;

for (const [key, value] of Object.entries(deps)) {
const res = value.find(x => x.target === 'find-me').source;
console.log(res); // expected: 'return-me'
}

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

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