[英]How do we get all property values from a JSON with name ID but has a specific parent object
I have a JSOn with multiple id value and I need to get an array out of all id values with parent 'parent4'我有一个具有多个 id 值的 JSOn,我需要从父级为“parent4”的所有 id 值中获取一个数组
I did this and it returns me all id values in an array我这样做了,它返回数组中的所有 id 值
function findAllByKey(obj, keyToFind) {
return Object.entries(obj).reduce(
(acc, [key, value]) =>
key === keyToFind
? acc.concat(value)
: typeof value === "object"
? acc.concat(findAllByKey(value, keyToFind))
: acc,
[]
);
}
But I just need those IDs with parent 'parent4' My output should be ['this is needed1', 'this is needed2', 'this is needed3', 'this is needed4']
但我只需要那些父级为“parent4”的 ID 我的输出应该是['this is needed1', 'this is needed2', 'this is needed3', 'this is needed4']
Here is the codesandbox link这是codesandbox链接
https://codesandbox.io/s/determined-noyce-0jgzj0?file=/src/App.js https://codesandbox.io/s/determined-noyce-0jgzj0?file=/src/App.js
I'm mostly making use of your own code here.我在这里主要使用您自己的代码。
First look for the parents you need:先寻找你需要的父母:
const resultParent = findAllByKey(myObj, "parent4");
Then input the result and get the ids you are looking for:然后输入结果,得到你要找的ids:
const result = findAllByKey(resultParent, "@id");
And then:接着:
console.log(result)
will output: ["this is needed1", "this is needed2", "this is needed3", "this is needed4"]
console.log(result)
会输出: ["this is needed1", "this is needed2", "this is needed3", "this is needed4"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.