gpt4 book ai didi

javascript - 如何向此嵌套 JSON 对象添加追加

转载 作者:行者123 更新时间:2023-12-02 19:55:27 26 4
gpt4 key购买 nike

我的 JSON 对象是

"msg"=[{"userName":"Mandy","emailId":"m@t.co","userCreated":"2011-12-21 17:21:49","allowedDownloads":"15"},{"userName":"Andy","emailId":"ab@r.co","userCreated":"2011-12-21 17:29:58","allowedDownloads":"45"},{"userName":"Randy","emailId":"re@t.co","userCreated":"2012-01-02 10:18:19","allowedDownloads":"15"},{"userName":"Vandy","emailId":"vai@t.co","userCreated":"2012-01-02 15:49:20","allowedDownloads":"14"},{"userName":"Sandy","emailId":"vrush@t.co","userCreated":"2012-01-02 16:47:35","allowedDownloads":"14"}]

1)如何再添加 1 个人以便附加“msg”

{"userName":"Wendy","emailId":"w@t.co","userCreated":"2012-12-21 17:21:49","allowedDownloads":"15"}

2)如何向每个索引添加属性“爱好”,以便我拥有,例如<​​/p>

{"userName":"Wendy","emailId":"w@t.co","userCreated":"2012-12-21 17:21:49","allowedDownloads":"15","hobbies":"skiing,football,hockey"}

3) 如何查看索引“Wendy”是否有爱好“曲棍球”?

最佳答案

因为你有一个 Javascript 数组

  var msg = [{"userName":"Mandy","emailId":"m@t.co","userCreated":"2011-12-21 17:21:49","allowedDownloads":"15"},
{"userName":"Andy","emailId":"ab@r.co","userCreated":"2011-12-21 17:29:58","allowedDownloads":"45"},
{"userName":"Randy","emailId":"re@t.co","userCreated":"2012-01-02 10:18:19","allowedDownloads":"15"},
{"userName":"Vandy","emailId":"vai@t.co","userCreated":"2012-01-02 15:49:20","allowedDownloads":"14"},
{"userName":"Sandy","emailId":"vrush@t.co","userCreated":"2012-01-02 16:47:35","allowedDownloads":"14"}];

您可以轻松推送新元素

  msg.push({"userName":"Wendy","emailId":"w@t.co","userCreated":"2012-12-21 17:21:49","allowedDownloads":"15"});

但是要更新记录,您必须循环

  function update(username, property, value){

for(var i=0; i < msg.length; i++){
var user = msg[i];
if(user["userName"] == username){
user[property] = value;
break;
}
}

}

要搜索,您还必须循环

  function check(username, property, value){

for(var i=0; i < msg.length; i++){
var user = msg[i];
if(user["userName"] == username){
var propertyVal = user[property];
if( propertyVal && propertyVal.indexOf(value) != -1){
return true;
}
}
}
return false;
}

关于javascript - 如何向此嵌套 JSON 对象添加追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8700608/

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