Javascript将新键值添加到JSON

时间:2013-12-29 23:23:46

标签: javascript json

我有这样的JSON:

[   {
        "RowID": "1",
        "Name": "Jack",
        "Age": "32",
        "Profesion": "ddddd",
        "Adress": "mmmmmm"
    },
    {
        "RowID": "2",
        "Name": "Joe",
        "Age": "17",
        "Profesion": "oooooo",
        "Adress": "xxxxxxxxxx"
    },
    {
        "Name": "Joe",
        "Age": "17",
        "Profesion": "oooooo",
        "Adress": "xxxxxxxxxx"
    },
    {
        "Name": "mike",
        "Age": "25",
        "Profesion": "ssssss",
        "Adress": "tttttt"
    }
]

如何在此JSON中的每个键/值"RowID": "New之前添加键/值"Name":"..."“,以及如何循环使用仅{{1}的所有键/值}?

2 个答案:

答案 0 :(得分:1)

我就是这样做的:

var arr = [   {
        "RowID": "1",
        "Name": "Jack",
        "Age": "32",
        "Profesion": "ddddd",
        "Adress": "mmmmmm"
    },
        {
            "RowID": "2",
            "Name": "Joe",
            "Age": "17",
            "Profesion": "oooooo",
            "Adress": "xxxxxxxxxx"
        },
        {
            "Name": "Joe",
            "Age": "17",
            "Profesion": "oooooo",
            "Adress": "xxxxxxxxxx"
        },
        {
            "Name": "mike",
            "Age": "25",
            "Profesion": "ssssss",
            "Adress": "tttttt"
        }
    ];

    arr = arr.map(function(obj){
       if(obj.hasOwnProperty('RowID')){
          obj.RowID = "Old";
       }
       else{
          obj.RowID = "New";
       }
        return obj;
    });
    console.log(arr);

    var newObjs = arr.filter(function(obj){ return obj.RowID === "New" });
    console.log(newObjs);

答案 1 :(得分:0)

// Give a RowID to each element that doesn't already have one.
list.forEach(function (item) {
  if (item.RowID === undefined) {
    item.RowID = 'New';
  }
});

// filter out new elements and loop through them
list.filter(function (item) {
  return item.RowID === 'New';
}).forEach(function (item) {
  console.log(item);
});