var d = [{id:1,name:"a",type:true},{id:2,name:"b",type:true},{id:3,name:"c",type:true},{id:4,name:"a",type:false}];
var done = [];
$.each(d, function(i,obj) {
if(obj.type == true) {
done.push({name:obj.name});
}
});
如何根据其属性name
?
答案 0 :(得分:2)
您可以使用临时对象c
缓存name
属性:
var d = [{ id: 1, name: "a", type: true }, { id: 2, name: "b", type: true }, { id: 3, name: "c", type: true }, { id: 4, name: "a", type: false }];
var done = [];
var c = {}; // cache for storing 'name' properties that was added to 'done' array
$.each(d, function(i, obj) {
if (obj.type && !c[obj.name]) { // it checks if the cache not contains this 'name'
done.push({ name: obj.name });
c[obj.name] = 'added'; // mark name that added to array
}
});
document.write(JSON.stringify(done));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:1)
您可以将名称存储在数组中,检查当前对象名称是否在存储对象名称的数组中
var d = [{
id: 1,
name: "a",
type: true
}, {
id: 2,
name: "b",
type: true
}, {
id: 3,
name: "c",
type: true
}, {
id: 4,
name: "a",
type: false
}, {
id: 5,
name: "a",
type: true
}];
var done = [], names = [];
$.each(d, function(i, obj) {
if (obj.type == true && $.inArray(obj.name, names) === -1) {
names.push(obj.name)
done.push({
name: obj.name
});
}
});
names.length = 0;
console.log(done)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
或者,使用$.unique()
,$.map()
,$.grep()
var d = [{
id: 1,
name: "a",
type: true
}, {
id: 2,
name: "b",
type: true
}, {
id: 3,
name: "c",
type: true
}, {
id: 4,
name: "a",
type: false
}, {
id: 5,
name: "a",
type: true
}];
var unique = $.unique($.map(d, function(obj, index) {
return obj.name
})),
done = $.grep(d, function(item, index) {
return item.name === unique[index] && index < unique.length ? {
name: item.name
} : null
})
console.log(done)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
答案 2 :(得分:0)
如果您只想从d
获取不同的名称,则可以执行
var tmp ={};
d.forEach(function(obj){
if(obj.type==true) tmp[obj.name]=1;
});
var done = Object.keys(tmp).map(function(name){
return {name: name};
});