如何在所有数组字段中添加一个元素?

时间:2016-09-23 12:19:35

标签: javascript angularjs json html5

SELECT * FROM TrackedEntityInstance ORDER BY field(localId,$string)

这是我的代码!!,我的问题是"如何添加" SPOC:987654321"进入所有领域?

4 个答案:

答案 0 :(得分:1)

您可以使用Array#forEach,然后仅应用带有值的属性。

var employees = [{ name: "Praveen", dateofbirth: new Date("July 24, 1992"), gender: "Male", salary: 12000, city: "Salem" }, { name: "Divya", dateofbirth: new Date("July 21, 1994"), gender: "Female", salary: 13500.33, city: "Thirupur" }, { name: "Elangovan", dateofbirth: new Date("May 5, 1989"), gender: "Male", salary: 14050.45, city: "Namakkal" }, { name: "Abinaya", dateofbirth: new Date("August 21, 1991"), gender: "Female", salary: 15230.78, city: "Thirupur" }, { name: "Surendran", dateofbirth: new Date("July 3, 1993"), gender: "Male", salary: 16302.44, city: "vellur" }, { name: "Hindhuja", dateofbirth: new Date("November 05, 1995"), gender: "Female", salary: 17000.11, city: "Salem" }];

employees.forEach(function (a) {
    a.SPOC = 987654321;
});

console.log(employees);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

employees.map(function (a) {
   a['SPOC'] = 987654321;
});

使用map方法并添加属性。

演示:https://jsbin.com/xofaka/edit?html,js,console

答案 2 :(得分:0)

employees.forEach(function(v, k) {
    v.SPOC = 987654321;
});

通过使用函数(v,k),您可以访问当前对象的值和键。有关 .forEach()的更多信息,请参见here

答案 3 :(得分:0)

        employees .forEach(function (item) {
          addSpoc(item);
                 })


     function addSpoc(item) {

        for (var i = 0, len = item.length; i < len; i++) {
          item[i].spoc = "987654321";
          // or  item[i]["spoc"] = "987654321";
              }