gpt4 book ai didi

javascript - 在嵌套的 json 对象中查找和更新

转载 作者:数据小太阳 更新时间:2023-10-29 04:04:31 25 4
gpt4 key购买 nike

我使用此代码从 sJhonny's Question 的 json 对象中找到所需的部分

数据样本

TestObj = {
"Categories": [{
"Products": [{
"id": "a01",
"name": "Pine",
"description": "Short description of pine."
},
{
"id": "a02",
"name": "Birch",
"description": "Short description of birch."
},
{
"id": "a03",
"name": "Poplar",
"description": "Short description of poplar."
}],
"id": "A",
"title": "Cheap",
"description": "Short description of category A."
},
{
"Product": [{
"id": "b01",
"name": "Maple",
"description": "Short description of maple."
},
{
"id": "b02",
"name": "Oak",
"description": "Short description of oak."
},
{
"id": "b03",
"name": "Bamboo",
"description": "Short description of bamboo."
}],
"id": "B",
"title": "Moderate",
"description": "Short description of category B."
}]
};

查找函数

function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}

像这样使用:

getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects

这段代码是从源中选择匹配的片段。但我想要的是用新值更新源对象并检索更新后的源对象。

我想要类似的东西

getObjects(TestObj, 'id', 'A', 'B'); // Returns source with updated value. (ie id:'A' updated to id:'B' in the returned object)

我的代码

function getObjects(obj, key, val, newVal) {
var newValue = newVal;
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
obj[key] = 'qwe';
}
}
return obj;
}

如果我给 obj[key] = 'qwe';,这会起作用,但如果我将代码更改为 obj[key] = newValue;,它会更新为未定义。

为什么会这样?

最佳答案

你忘记在嵌套调用中传递 newValue

function getObjects(obj, key, val, newVal) {
var newValue = newVal;
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val, newValue));
} else if (i == key && obj[key] == val) {
obj[key] = 'qwe';
}
}
return obj;
}

关于javascript - 在嵌套的 json 对象中查找和更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17988939/

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