gpt4 book ai didi

javascript - 如何递归查找对象键是否存在?

转载 作者:行者123 更新时间:2023-11-30 19:48:18 26 4
gpt4 key购买 nike

我有以下对象

acn: "02 0002 0002"
id: "random"
name: "random"
parent_domain: "parent-random"
subDomainData: {random-l3.1: {…}}
sub_domains: ["random-l3.1"]
timestamp: 1549597441

subDomainData 是另一个可能存在或不存在的对象。如果它存在,它可以有另一个 subDomainData,它可以有一个或多个 child ,也可以没有,依此类推。

我的疑问是如何创建一个函数来递归检查它,如果为真,则将其对象推送到另一个数组;预期的最终数组将是这样的:

[
{
acn: "02 0002 0002"
id: "random"
name: "random"
parent_domain: ""
sub_domains: ["random-l3.1"]
timestamp: 1549597441
},
{ // this object would be the result of the parent subDomainData Object.
acn: "02 0002 0002"
id: "random-sub-1"
name: "random-sub-1"
parent_domain: "parent-random"
sub_domains: ["random-l3.3"]
timestamp: 1549597441
}
]

现在我正在遵循这种方法,但事实证明这是不够的:

formatDomainList = () => {
const { domain } = this.props;
const domainList = Object.values(domain.subDomainData);
domainList.map(item => (
Object.keys(item.subDomainData).length && (
domainList.push(item.subDomainData)
)
//etc
//etc
));
// console.log('domain list', domainList);

最佳答案

这样的东西对你有用:

//This is your original object
var someObject = {
acn: "02 0002 0002",
id: "random",
name: "random",
parent_domain: "parent-random",
subDomainData: { someObjectWith_subDomainData },
sub_domains: ["random-l3.1"],
timestamp: 1549597441
};
//This will store the list of subDomains in this global variable.
var subDomainList = [];

function getSubDomainList(objectToLoop){

if(objectToLoop.hasOwnProperty('subDomainData')){
var numOfItems = Object.keys(objectToLoop.subDomainData).length;
var keys = Object.keys(objectToLoop.subDomainData);
for(var i = 0; i< numOfItems; i++){
var key = keys[i];
var obj = objectToLoop.subDomainData[key];
subDomainList.push(obj);
getSubDomainList(obj);
}
}
return;
}

getSubDomainList(someObject);
//The subDomainList will have the array of objects.

关于javascript - 如何递归查找对象键是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54741308/

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