简体   繁体   English

将项目添加到JSON对象

[英]Add items to JSON object

I'm picking up a JSON object using a promise: 我正在使用promise来获取JSON对象:

var x = get();
x.done(function(data) {
    for(var i in data) {

    }
});

which is returning this data when i do console.log(data); 当我执行console.log(data);时返回的数据

[{…}]
0:
customer: "9028"
data:
active: "1"
customer: "9028"
description: ""
id: "13717"
inherited: "0"
name: "Out of Hours"
priority: "1"
shared: "0"
sound: ""
__proto__: Object
voip_seq: "4"
__proto__: Object
length: 1
__proto__: Array(0)

so that is working fine, but within my for loop, I want to add 2 items to data 这样就可以了,但是在我的for循环中,我想向data添加2个项目

I tried adding this into my .done 我尝试将其添加到我的.done

var obj = { name: "Light" };
data.push(obj);

But that didn't add to data 但这并没有增加data

My for loop looks like this: 我的for循环如下所示:

                 for(var i in data) {
                    var m = '<option value="' + data[i].data.id + '"'
                    if(data[i].data.id == selected_val) {
                        m += ' selected="selected"';
                    }
                    m += '>' + data[i].data.name + '</option>';
                    $('#' + value_element_id).append(m);
                }

If you want to add two more items to your select, you simply need to push new objects into your data array before your loop starts. 如果要在选择中再添加两个项目,则只需在循环开始之前将新对象推送到data数组中即可。 The objects must contain the structure and properties ("name" and "id" within a "data" sub-property) matching the JSON coming from the Promise, so that your loop code can process them. 这些对象必须包含与来自Promise的JSON匹配的结构和属性(“数据”子属性中的“名称”和“ id”),以便您的循环代码可以处理它们。

In the simplest case, it could be as straightforward as 在最简单的情况下,它可能像

x.done(function(data) {
  data.push({ "data": { "name": "light", "id": 1234 } });
  data.push({ "data": { "name": "dark", "id": 5678 } });

  for(var i in data) {
    var m = '<option value="' + data[i].data.id + '"'
    if (data[i].data.id == selected_val) {
      m += ' selected="selected"';
    }
    m += '>' + data[i].data.name + '</option>';
    $('#' + value_element_id).append(m);
  }
});

Demo: https://jsfiddle.net/a286b7fw/1/ 演示: https : //jsfiddle.net/a286b7fw/1/

In this case I think data is not an array so it hasn't .push() method. 在这种情况下,我认为data不是数组,因此它没有.push()方法。 You can add property to object like this: 您可以像这样向对象添加属性:

for(var i in data) {
  var m = '<option value="' + data[i].data.id + '"'
  if(data[i].data.id == selected_val) {
    m += ' selected="selected"';
  }
  m += '>' + data[i].data.name + '</option>';
  $('#' + value_element_id).append(m);

  // here it will add obj to data
  var obj = {name: "Light"};
  data = {
    ...data,
    obj
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM