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

时间:2014-04-26 03:43:47

标签: javascript php object

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

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

4 个答案:

答案 0 :(得分:2)

使用array.mapAdded to the ECMA-262 standard in the 5th edition):

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

Example Here

更新:它可能是一个数组

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

Example2 Here.

答案 1 :(得分:1)

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;

答案 2 :(得分:1)

它们看起来像JSON数据,所以json_decode()到一个数组,搜索UId值,然后添加相应的assoc值,在结束之后最终使用json_encode() <将它们包起来/ p>

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"
    }
]

答案 3 :(得分:1)

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

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

或者您可以使用filter功能。

// 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";
}