2017-09-23 102 views
0

我有这样获取场阵列的独特价值

[{ 
    Item: pen, 
    Color: blue, 
    Brand: cello 
},{ 
    Item: pen, 
    Color: red, 
    Brand: cello 
},{ 
    Item: pen, 
    Color: blue, 
    Brand: cello 
}] 

我想要的结果数组像

[{ 
    Item: pen, 
    Brand: cello 
}] 

我需要从数组中删除一个属性“颜色”,并得到独特的价值。有人能帮我实现这个输出吗?

回答

1

您可以保留一个新的空数组,将每个对象的原始数组删除颜色键迭代,并将其推送到新数组(如果它不在新数组中)。

var arr = [{Item: 'pen', Color: 'blue', Brand: 'cello'}, {Item: 'pen', Color: 'red', Brand: 'cello'}, {Item: 'pen', Color: 'blue', Brand: 'cello'}]; 
 

 
var newArr = []; 
 
arr.forEach(x => { 
 
    delete x.Color 
 
    for(var i=0; i<newArr.length; i++) 
 
     if(newArr[i].Item === x.Item && newArr[i].Brand === x.Brand) 
 
     return; 
 
    newArr.push(x); 
 
}); 
 

 
console.log(newArr);

0

您可以使用array#reducearray#some。使用delete从对象中删除Color属性。

var arr = [{ Item: 'pen',Color: 'blue',Brand: 'cello'},{Item: 'pen',Color: 'red',Brand: 'cello'},{Item: 'pen',Color: 'blue',Brand: 'cello'}]; 
 

 

 
var uniq = arr.reduce(function(u, o1){ 
 
    delete o1.Color; 
 
    var isExist = u.some(function(o2){ 
 
    return o2.Item === o1.Item && o2.Brand === o1.Brand; 
 
    }); 
 
    if(!isExist) 
 
    u.push(o1); 
 
    return u; 
 
},[]); 
 

 
console.log(uniq);

0

可以映射在阵列中的每个对象,并指定其值,以一个新的对象。这个新对象可以将颜色键删除并推送到不同的阵列。

var array = [{ 
 
    Item: 'pen', 
 
    Color: 'blue', 
 
    Brand: 'cello' 
 
},{ 
 
    Item: 'pen', 
 
    Color: 'red', 
 
    Brand: 'cello' 
 
},{ 
 
    Item: 'pen', 
 
    Color: 'blue', 
 
    Brand: 'cello' 
 
}]; 
 

 
const newArray = []; 
 
array.map(obj => { 
 
    let newObject = Object.assign({}, obj); 
 
    delete newObject.Color; 
 
    if(newArray.length) { 
 
    newArray.map(newObj => { 
 
     if(newObj.Item !== newObject.item && newObj.Brand !== newObject.Brand) { 
 
     newArray.push(newObject); 
 
     } 
 
    }); 
 
    } else { 
 
    newArray.push(newObject); 
 
    } 
 
}); 
 

 
console.log(array); 
 
console.log(newArray);