以编程方式添加数组的对象属性


programmatically add object properties of arrays

[
    {
        "uId": "2",
        "tabId": 1,
        "tabName": "Main",
        "points": "10"
    },
    {
        "uId": "3",
        "tabId": 2,
        "tabName": "Photography",
        "points": "20"
    }
]

如何通过检查指定数组的属性值来插入该数组?说我想在uId=3中添加一个assoc对象,我该怎么做?还是技术上不可能?

这也可以使用array.map(Added to the ECMA-262 standard in the 5th edition(:

array.map(function(i){
    if(i.uId == 3) i['newprop'] = 'newValue';
});

示例如下。

更新:它可能是一个阵列

if(i.uId == 3) i['newprop'] = ['newvalue1', 'newvalue2'];

示例2在这里。

它们看起来像JSON数据,所以json_decode()到一个数组,搜索UId值,然后添加相应的assoc值,最后使用json_encode() 将它们封装起来

foreach($array as $k=>&$arr)
{
    if($arr->{'uId'}==2)
    {
        $arr->{'somecol'}="Hey";
    }
}
echo json_encode($array,JSON_PRETTY_PRINT);

OUTPUT :

[
    {
        "uId": "2",
        "tabId": 1,
        "tabName": "Main",
        "points": "10",
        "somecol": "Hey"
    },
    {
        "uId": "3",
        "tabId": 2,
        "tabName": "Photography",
        "points": "20"
    }
]
var array = [
    {
        "uId": "2",
        "tabId": 1,
        "tabName": "Main",
        "points": "10"
    },
    {
        "uId": "3",
        "tabId": 2,
        "tabName": "Photography",
        "points": "20"
    }
];
for ( var i = 0; i < array.length; i++ ) {
    if ( array[i].uId == 3) {
        array[i].someProp = "Hello";
        break; // remove this line for multiple updates
    }
}

或者你可以做一个这样的函数:

function getMatch(data, uid) {
    for ( var i = 0; i < data.length; i++ ) {
        if ( data[i].uId == 3) {
            return data[i];
        }
    }
}

并像这样使用:

getMatch(array, 3).someproperty = 4;

您可以使用map函数,它对数组的每个元素执行一个函数

a.map(function(el) { 
  if (el.uId == 3) {
    el.prop = "value";
  }
});

或者您可以使用过滤器功能。

// Get the array of object which match the condition
var matches = a.filter(function(x) { return x.uId == 3 });
if (matches.length > 0) {
    matches[0].prop = "value";
}