【问题标题】:programmatically add object properties of arrays以编程方式添加数组的对象属性
【发布时间】:2014-06-11 22:49:06
【问题描述】:
[
    {
        "uId": "2",
        "tabId": 1,
        "tabName": "Main",
        "points": "10"
    },
    {
        "uId": "3",
        "tabId": 2,
        "tabName": "Photography",
        "points": "20"
    }
]

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

【问题讨论】:

标签: javascript php object


【解决方案1】:

它们看起来像 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"
    }
]

【讨论】:

  • $array =json_decode($json,true);我的 $json 已经是一个数组,但是当我使用它时,它说 json_decode() 期望参数 1 是字符串,数组给定 i
  • 那就不要$array =json_decode($json,true);,直接运行foreach的代码
  • 不能使用 stdClass 类型的对象作为数组
  • @user3522444,请查看编辑后的答案。 (已测试)
【解决方案2】:

这也可以使用array.map (Added 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.

【讨论】:

  • 'newValue' 可以是一个数组吗?
  • 是的,它可以是一个数组@user3522444。
【解决方案3】:

您可以使用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";
}

【讨论】:

  • 抱歉,你是版主,但我在选举中没有注意到你,但我可能是错的,无论如何,欢迎 :-)
【解决方案4】:
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;

【讨论】:

  • 你也可以在for循环后面加上console.log(JSON.stringify(array));来查看你更新的数组
猜你喜欢
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多