如何在遍历数组时添加JSON对象

时间:2018-06-20 17:22:46

标签: jquery

我有一个JSON,如下所示

var json = [{
        "name": "John",
        "city": "New York"
      },
      {
        "name": "SAAA",
        "city": "California"
      },
      {
        "name": "Vignesh",
        "city": "India"
      }];

我正在使用forEach遍历JSON,而在循环中如果name等于'SAAA',我试图插入状态为

这样最终的JSON看起来就像

[{
        "name": "John",
        "city": "New York"
      },
      {
        "name": "SAAA",
        "city": "California",
       "status": true
      },
      {
        "name": "Vignesh",
        "city": "India"
      }];

我的代码

json.forEach(function(element) {
                var jsonname = element.name;
                if(jsonname==name)
                {
                json.status = true;
                }
                });

        alert(JSON.stringify(json));

请告诉我如何向JSON添加状态?

https://jsfiddle.net/o2gxgz9r/51200/

2 个答案:

答案 0 :(得分:1)

element是循环中的当前元素。要添加或更改属性,您可以element.status = true;

var json = [{
    "name": "John",
    "city": "New York"
  },
  {
    "name": "SAAA",
    "city": "California"
  },
  {
    "name": "Vignesh",
    "city": "India"
  }
];

var name = "SAAA";
json.forEach(function(element) {
  var jsonname = element.name;
  if (jsonname == name) {
    element.status = true; //To update or add a property of the object. Use element.status 
  }
});

console.log(json);

答案 1 :(得分:0)

尝试这样的事情:

$(document).ready(function() {

  var json = [{
      "name": "John",
      "city": "New York"
    },
    {
      "name": "SAAA",
      "city": "California"
    },
    {
      "name": "Vignesh",
      "city": "India"
    }
  ];

  var name = 'SAAA';

  json.forEach(function(element, index) {
    var jsonname = element.name;
    if (jsonname == name) {
      json[index].status = true;
    }
  });

  alert(JSON.stringify(json));


});
body {
  padding: 5px;
}

label {
  font-weight: bold;
}

input[type=text] {
  width: 20em
}

p {
  margin: 1em 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="search_field">Address</label>
<input type='text' class='address_field' />