比较和更改两个对象数组

时间:2019-06-06 07:54:22

标签: javascript arrays object ecmascript-6

我想比较两个数组的每个对象。如果array1的属性名称与array2的属性名称匹配,则从array1更改array2的值。

{ "objectID": 10202, "gm_url": "myurl", "results": [{ "marque": "Alfa", "model": "Romeo Giulia Sprint GT Veloce 1600", "model_year": "1966", "price_str": "€49 280", "price_int": 49280, "price_currency": "€", "sold": true, "auction_house": "RM Sotheby's", "auction_country": "Italy", "auction_date": "25 - 27 November 2016", "auction_datetime": "2016-11-27", "auction_url": null, "image_urls": "imagesurl" }, { "marque": "Alfa", "model": "Romeo Giulia Sprint GT Veloce Coupe", "model_year": "1966", "price_str": "€46 000", "price_int": 46000, "price_currency": "€", "sold": true, "auction_house": "Bonhams", "auction_country": "France", "auction_date": "6 February 2014", "auction_datetime": "2014-02-06", "auction_url": "https://www.bonhams.com//auctions/21768/lot/434/?category=list&length=100000&page=1", "image_urls": "imagesurl" }] }

期望从array2返回一个新的数组-

let array1 = [{
        name: 'test1',
        values: ['a', 'b', 'c']
    },
    {
        name: 'test2',
         values: ['w,','q','q' ]
    }
]

let array2 = [{
        name: 'test1',
        items: '...',
        settings: '...',
        values: []
    },
    {
        name: 'test9',
        items: '...',
        settings: '...',
        values: []
    },

    {
        name: 'test10',
        items: '...',
        settings: '...',
        values: []
    },

    {
        name: 'test2',
        items: 'test2',
        settings: '...',
        values: []
    },
]

我尝试了嵌套地图。变得凌乱。 在此先感谢:)

5 个答案:

答案 0 :(得分:2)

使用mapfind

let array1 = [{name:'test1',values:['a','b','c']},{name:'test2',values:['w,','q','q']}];
let array2 = [{name:'test1',items:'...',settings:'...',values:[]},{name:'test9',items:'...',settings:'...',values:[]},{name:'test10',items:'...',settings:'...',values:[]},{name:'test2',items:'test2',settings:'...',values:[]},];

const res = array2.map(e => {
  let found = array1.find(({ name }) => name == e.name);
  if (found) e.values = found.values;
  return e;
});

console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

答案 1 :(得分:1)

您还可以使用filter来获得如下结果:

let array1 = [{name:'test1',values:['a','b','c']},{name:'test2',values:['w,','q','q']}];
let array2 = [{name:'test1',items:'...',settings:'...',values:[]},{name:'test9',items:'...',settings:'...',values:[]},{name:'test10',items:'...',settings:'...',values:[]},{name:'test2',items:'test2',settings:'...',values:[]},];

var array2new = array2.filter(function(obj2) {
    return array1.filter(function(obj1) {
        if(obj1.name == obj2.name){
          return obj2.values.push(obj1.values);
        }else{return obj2;}
    });
});
console.log(array2new)

答案 2 :(得分:0)

您可以使用reduce来解决这个问题。

let array1 = [{
        name: 'test1',
        values: ['a', 'b', 'c']
    },
    {
        name: 'test2',
        values: ['w,','q','q' ]
    }
]

let array2 = [{
        name: 'test1',
        items: '...',
        settings: '...',
        values: []
    },
    {
        name: 'test9',
        items: '...',
        settings: '...',
        values: []
    },

    {
        name: 'test10',
        items: '...',
        settings: '...',
        values: []
    },

    {
        name: 'test2',
        items: 'test2',
        settings: '...',
        values: []
    },
]
const newArray2 = array2.reduce((newArray, currentObj) => {
  array1.forEach(baseObj => {
    if((baseObj.name == currentObj.name) && baseObj.values) {
      currentObj.values = baseObj.values;
    }
  })
  newArray.push(currentObj);
  return newArray;
}, [])

console.log(newArray2);

答案 3 :(得分:0)

您可以使用Map并将找到的对象分配给最终对象。

var array1 = [{ name: 'test1', values: ['a', 'b', 'c'] }, { name: 'test2', values: ['w,', 'q', 'q'] }],
    array2 = [{ name: 'test1', items: '...', settings: '...', values: [] }, { name: 'test9', items: '...', settings: '...', values: [] }, { name: 'test10', items: '...', settings: '...', values: [] }, { name: 'test2', items: 'test2', settings: '...', values: [] }],
    map = new Map(array1.map(o => [o.name, o])),
    result = array2.map(o => Object.assign({}, o, map.get(o.name)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 4 :(得分:0)

我也建议您使用Array#reduce方法:

let array1 = [{
    name: 'test1',
    values: ['a', 'b', 'c']
  },
  {
    name: 'test2',
    values: ['w,', 'q', 'q']
  }
]

let array2 = [{
    name: 'test1',
    items: '...',
    settings: '...',
    values: []
  },
  {
    name: 'test9',
    items: '...',
    settings: '...',
    values: []
  },

  {
    name: 'test10',
    items: '...',
    settings: '...',
    values: []
  },

  {
    name: 'test2',
    items: 'test2',
    settings: '...',
    values: []
  },
]

let arr = [...array2, ...array1].reduce((a,c) => {
	let filtered = a.filter(el => el.name === c.name);
	if(filtered.length){
		Object.assign(filtered[0], c);
	}else{
		a.push(c);
	}
	return a;
}, []);

console.log(JSON.stringify(arr));