gpt4 book ai didi

javascript - 操作 JSON 对象 : how to reference and update nested values

转载 作者:行者123 更新时间:2023-11-30 17:59:02 25 4
gpt4 key购买 nike

我才刚刚开始,所以我对如何使用以下内容感到困惑。

// so I believe this really isn't an object just a string representation, but for example please excuse the name
var dataObj = "{'id': 1,
'data': { 'color': 'red',
'shape' : 'triangle',
'height' : 100,
'width' : 45,
},
'id': 2,
'data': { 'color': 'blue',
'shape' : 'square',
'height' : 75,
'width' : 67,
},
'id': 3,
'data': { 'color': 'orange',
'shape' : 'circle',
'height' : 89,
'width' :24,
}
}";

所以我遇到的问题是如何通过 id 更新数据值的特定子集(比如 SQL UPDATE WHERE 之类的东西)? javascript 或 jquery 对我来说真的不重要,只是不知道两者的方法。

dataObjUpdate(2);    
function dataObjUpdate (passedID) {

//access the data by the passedID match and update the color to black
}

感谢大家的帮助....

最佳答案

如果我们忽略我留下的评论并假设您有一个 JavaScript 对象。我看到以下问题:

  • 您的 ID 在嵌套对象之外。
  • 您正在使用一个对象,但您想要一个“列表”,您可以为此使用一个数组。

这是我自己构建对象的方式:

var data = [{ 
color : 'red',
shape : 'triangle',
height : 100,
width : 45,
id:1
},
{
color: 'blue',
shape : 'square',
height : 75,
width : 67,
id: 2
},
{
color: 'orange',
shape : 'circle',
height : 89,
width :24,
id :3
}];

现在,我可以像您期望的那样使用 filter 查询它:

var id3 = data.filter(function(elem){
return elem.id === 3;
})[0];
id3;//the third object, with id 3

ES6 有一个名为 find 的方法,它会将 [0] 保存在末尾(这意味着第一个元素)

var id3 = data.find(function(elem){
return elem.id === 3;
});
id3;//the third object, with id 3

或者,您可以使用一个简单的 for 循环

var id3 = (function find(arr){
for(var i=0;i<arr.length;i++){
if(arr[i].id === 3){
return arr[i];
}
}
})(data);
id3;

关于javascript - 操作 JSON 对象 : how to reference and update nested values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17489143/

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