向数组内的现有对象添加属性

时间:2016-09-22 12:15:37

标签: javascript angularjs arrays object javascript-objects

我从外部文件中选择一个包含很少对象的数组。

使用:

app.controller('mycontroller',  function($scope, $http) { 
$http.get("file")
.then(function(response) {
    $scope.lols = response.data;     
});});

这会让我回复:

 $scope.lols = [
{
    prop1: "h1",
    prop2: "h2",
},
{
    prop1: "g1",
    prop2: "g2",
},}

现在我想在每个对象中添加prop3我应该怎么做?如果我将数据存入我的js文件,我将手动完成,但从外部文件中选择数据......

我尝试过这样做:

app.controller('mycontroller',  function($scope, $http) { 
$http.get("file")
.then(function(response) {
    $scope.lols = response.data;
    $scope.lols.push = [
    {prop3: "h3"},
    {prop3: "g3"}
    ]
});});

但它没有奏效......

感谢您提供任何帮助或链接解释。

解: https://jsfiddle.net/d3c96e0z/3/

5 个答案:

答案 0 :(得分:1)

我认为这应该对你有帮助: -

var lols = [
{
    prop1: "h1",
    prop2: "h2",
},
{
    prop1: "g1",
    prop2: "g2",
}
]

Object.keys(lols).map(function(key,index){
        var lol = lols[key]
      lol["props3"]="g3"
      console.log(lol)
})

JS小提琴链接https://jsfiddle.net/bps7zzf8/

答案 1 :(得分:0)

试试,Here is working example  $scope.lols.push({prop1: "h3",prop2: "g3"});

答案 2 :(得分:0)

您希望prop3成为prop1prop2的兄弟姐妹吗? 如果是这样,您可以执行硬编码,例如:

$scope.lols[0].prop3 = "h3";
$scope.lols[1].prop3 = "g3";

或以更强烈的动态方式

var newProps = ["h3", "g3"];
for (var i = 0; i < $scope.lols.length; i++) {
  $scope.lols[i].prop3 = newProps[i]; // assuming the length of both arrays is the same size;
}

您的方法存在问题:使用push,您需要在数组中创建新索引,而不是将属性添加到现有索引中。

答案 3 :(得分:0)

如果要在每个对象中添加prop3,可以尝试以下过程:

// assume that you know "lols" length. here let 2 so add 2 values for prop3

$scope.prop3Values = ["yellow", "red"];

$scope.lols = $scope.lols.map(function(e,index) {
    e.prop3 = $scope.prop3Values[index]; // assign your value in prop3
    return e;
  });

然后您的lols看起来像

$scope.lols = [
{
    prop1: "h1",
    prop2: "h2",
    prop3: "yellow"
},
{
    prop1: "g1",
    prop2: "g2",
    prop3: "red"
}]

答案 4 :(得分:0)

保持要在对象数组中添加的属性,然后遍历$ scope.lols并根据索引添加每个属性;

$scope.propertyJson=[{prop3: "h3"},{prop3: "g3"}];
for (var i = 0; i < $scope.lols.length; i++) {
 angular.forEach($scope.propertyJson[i], function(value, key) {
  $scope.lols[i][key] = value;
 });
}
相关问题