例如

我有一个名为tempobj的对象,下面是tempobj[0]tempobj[1]样本数据。

我想添加其他信息,例如该对象的名称和状态

tempobj ["info"]["name"] = "title";
tempobj ["info"]["id"] = "23243";


但是当我做stringify时,jQuery忽略了这个值...我怎样才能将这样的数据添加到这种结构中。

 [
        [{
            "name": "Breakfast",
            "value": "buffalo strip ",
            "check": 0
        }, {
            "name": "snack ",
            "value": "pecan pie butter",
            "check": 0
        }, {
            "name": "dessert",
            "value": "chocolate zucchani brownie",
            "check": 0
        }],
        [{
            "name": "Breakfast",
            "value": "Stir Fried Kale and Baccon  ",
            "check": 1
        }, {
            "name": "snack ",
            "value": "Smoked Salmon nori roll  "
        }, {
            "name": "dessert",
            "value": "Apple muffins"
        }]

最佳答案

tempobj是一个数组([])。

当您尝试使用以下方法设置一些值时:

tempobj["info"]["name"] = "title";
tempobj["info"]["id"] = "23243";


您将其视为对象({})。

如果要向tempobj添加一些数据,则必须像这样更改其结构,例如:

{
    "info": {
        "name": "title",
        "id": "23243"
    },
    "items": [
        [{
            "name": "Breakfast",
            "value": "buffalo strip ",
            "check": 0
        }, {
            "name": "snack ",
            "value": "pecan pie butter",
            "check": 0
        }, {
            "name": "dessert",
            "value": "chocolate zucchani brownie",
            "check": 0
        }],
        [{
            "name": "Breakfast",
            "value": "Stir Fried Kale and Baccon  ",
            "check": 1
        }, {
            "name": "snack ",
            "value": "Smoked Salmon nori roll  "
        }, {
            "name": "dessert",
            "value": "Apple muffins"
        }]
    ]
}


这是一个示例:

var tempobj = {
    items: [
        [{
            "name": "Breakfast",
            "value": "buffalo strip ",
            "check": 0
        }, {
            "name": "snack ",
            "value": "pecan pie butter",
            "check": 0
        }, {
            "name": "dessert",
            "value": "chocolate zucchani brownie",
            "check": 0
        }],
        [{
            "name": "Breakfast",
            "value": "Stir Fried Kale and Baccon  ",
            "check": 1
        }, {
            "name": "snack ",
            "value": "Smoked Salmon nori roll  "
        }, {
            "name": "dessert",
            "value": "Apple muffins"
        }]
    ]
}

tempobj.info = {
    name: 'title',
    id: '23243'
};

// Another way:
//tempobj.info = {};
//tempobj.info.name = 'title';
//tempobj.info.id = '23243';

console.log(JSON.stringify(tempobj));

09-28 04:28