使用JavaScript将新属性(元素)添加到JSON对象

JavaScript

宝儿伽罗

2020-03-16

如何使用JavaScript将新属性(元素)添加到JSON对象?

第1699篇《使用JavaScript将新属性(元素)添加到JSON对象》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
ProA 2020.03.16

You can also add new json objects into your json, using the extend function,

var newJson = $.extend({}, {my:"json"}, {other:"json"});
// result -> {my: "json", other: "json"}

A very good option for the extend function is the recursive merge. Just add the true value as the first parameter (read the documentation for more options). Example,

var newJson = $.extend(true, {}, {
    my:"json",
    nestedJson: {a1:1, a2:2}
}, {
    other:"json",
    nestedJson: {b1:1, b2:2}
});
// result -> {my: "json", other: "json", nestedJson: {a1:1, a2:2, b1:1, b2:2}}
神无Davaid 2020.03.16
var jsonObj = {
    members: 
           {
            host: "hostName",
            viewers: 
            {
                user1: "value1",
                user2: "value2",
                user3: "value3"
            }
        }
}

var i;

for(i=4; i<=8; i++){
    var newUser = "user" + i;
    var newValue = "value" + i;
    jsonObj.members.viewers[newUser] = newValue ;

}

console.log(jsonObj);
阳光猿 2020.03.16

JSON代表JavaScript Object Notation。JSON对象实际上是一个字符串,尚未转换为它表示的对象。

要将属性添加到JS中的现有对象,可以执行以下操作。

object["property"] = value;

要么

object.property = value;

如果您提供一些额外的信息,例如您在上下文中确实需要做的事情,那么您可能会得到一个更量身定制的答案。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android