[
{
"uId": "2",
"tabId": 1,
"tabName": "Main",
"points": "10"
},
{
"uId": "3",
"tabId": 2,
"tabName": "Photography",
"points": "20"
}
]
如何通过检查其属性值来插入指定的数组?说我想在uId = 3中添加一个assoc对象,我该怎么做?或者技术上不可能?
答案 0 :(得分:2)
使用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'];
答案 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)