js 数组、数组对象去重、数组对象覆盖

// 数组去重
var sDataArray = ['1', '2', '3', '2', '1', '2'];
console.log([...new Set(sDataArray)]) // [ '1', '2', '3' ]
// 字符串去重
var sDataString = 'acdaaaddss'
console.log([...new Set(sDataString)]) // [ 'a', 'c', 'd', 's' ]
// 数组对象去重
var sDataObjectArray = [
    {'name': 'aaa', 'age': '12'},
    {'name': 'aaa1', 'age': '12'},
    {'name': 'aaa', 'age': '10'},
    {'name': 'bbb', 'age': '11'},
    {'name': 'aaa', 'age': '12'},
    {'name': 'aaa1', 'age': '12'},
    {'name': 'aaa2', 'age': '12'}
    ]
var result = [];
var obj = {};
// 使用obj来记录push过的值
for(var i =0; i < sDataObjectArray.length; i++){
    console.log(obj)
    if(!obj[sDataObjectArray[i].name]){
        result.push(sDataObjectArray[i]);
        obj[sDataObjectArray[i].name] = true;
    }
}
/**
 * [{ name: 'aaa', age: '12' },
 { name: 'aaa1', age: '12' },
 { name: 'bbb', age: '11' },
 { name: 'aaa2', age: '12' } ]

 */
console.log('-----------------------------------------------分割线-----------------------------------------------')
// 数组对象相同就覆盖
var dataObject = {'name': 'aaa', 'age': '18', 'test': 'test-aaa'}
var dataObjectArray = [{'name': 'aaa', 'age': '10'}, {'name': 'bbb', 'age': '11'}, {'name': 'ccc', 'age': '12'}]
dataObjectArray.forEach((val, key) => {
 if (val.name === dataObject.name) {
   Object.assign(val, dataObject);
 }
})
console.log(dataObjectArray)
/**
 * [ { name: 'aaa', age: '18', test: 'test-aaa' },
 { name: 'bbb', age: '11' },
 { name: 'ccc', age: '12' } ]
 */


 

你可能感兴趣的:(技术(javascript))