gpt4 book ai didi

javascript - 递归地重新创建嵌套对象数组

转载 作者:行者123 更新时间:2023-12-03 06:21:28 25 4
gpt4 key购买 nike

我有一个由用户创建的嵌套对象数组。我需要递归检查数组是否已检查设置为 true 并重新创建对象的嵌套数组,如下所示。

通过我最初的尝试,我能够递归地访问嵌套数组。然而,每次递归时我都会覆盖我以前的信息。

$scope.newPropertyTemplate = [];

function checkProps (item, props){
debugger
var obj = {};
var arr = [];

for(var i in props){

if(props[i].checked === true){
obj.property = item;
arr.push(props[i].name);
obj.subProperties = arr;
}

if(props[i].properties){
checkProps(props[i].name, props[i].properties);
}
}

return obj;
}

for(var i = 0; i < $scope.propertyTemplate.length; i++){

if($scope.propertyTemplate[i].properties !== null){

$scope.newPropertyTemplate.push(checkProps($scope.propertyTemplate[i].name, $scope.propertyTemplate[i].properties));
// $scope.newPropertyTemplate.push( newItem.property = $scope.propertyTemplate[i].name );
}
else {
$scope.newPropertyTemplate.push($scope.propertyTemplate[i].name);
}
}

这是嵌套数组的示例:

    [
{name: "allocation",
properties:[
{
name: "oid",
checked: true,
properties: null,
type: "integer"
},
{
name: "person",
checked: false,
properties: [
{
name: "Expires",
checked: true,
properties: null,
type: "timestamp"
},
{
name: "State/Province",
checked: true,
properties: null,
type: "string"
}
]
],
type: "allocation"
]

以下是转换后的对象数组的示例:

[
{property: "allocation",
subProperties: [
"oid",
{property: "person",
subProperties: [
"Expires",
"State/Province"
]
}
]
}
]

最佳答案

这应该有效。递归 checkProps 函数返回的 obj 未存储。

var data = [{
name: "allocation",
properties: [{
name: "oid",
checked: true,
properties: null,
type: "integer"
}, {
name: "person",
checked: false,
properties: [{
name: "Expires",
checked: true,
properties: null,
type: "timestamp"
}, {
name: "State/Province",
checked: true,
properties: null,
type: "string"
}]
},

],
type: "allocation"
}];

function process(paths) {
var arr = [];
data.forEach(function(template) {
var resultObj = {};
recurse(template, resultObj);
arr.push(resultObj);
});
console.log(arr);
}

function recurse(template, obj) {
obj.property = template.name;
if (template.properties == null)
return;
obj.subProperties = [];
template.properties.forEach(function(prop) {
var res = {};
if (prop.properties != null)
recurse(prop, res);
else if (prop.checked)
res = prop.name;
if (res)
obj.subProperties.push(res);
});;
}

process(data);

关于javascript - 递归地重新创建嵌套对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38856836/

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