从json数组中删除重复项

时间:2015-10-07 16:53:42

标签: arrays json duplicates unique

代码:

$decode = json_decode($get, TRUE);
    foreach($decode['List'] as $lst) {

    }

我有一个数组$ lst,看起来像这样:

"List":[{
    "Name":"Ivan",
    "Surname":"Petrov",
}, {
    "Name":"Ivan",
    "Surname":"Ivanov",
}, {
    "Name":"Andrey",
    "Surname":"Sidorov",
}]

我需要删除重复项,以便保留这样的内容(重复'Name'):

"List":[{
    "Name":"Ivan",
    "Surname":"Petrov",
}, {
    "Name":"Andrey",
    "Surname":"Sidorov",
}]

2 个答案:

答案 0 :(得分:0)

使用lodash

var list = [{
    "Name":"Ivan",
    "Surname":"Petrov",
}, {
    "Name":"Ivan",
    "Surname":"Ivanov",
}, {
    "Name":"Andrey",
    "Surname":"Sidorov",
}];

var noDupsList = _.uniq(list, 'Name');

alert(JSON.stringify(noDupsList));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

答案 1 :(得分:0)

我不认为存在预定义的功能来实现这一目标。

但是你通过迭代应用比较,并且可以使用delete运算符从json中删除一个 喜欢 删除x [0]