2017-09-23 120 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);