我有以下代码,该代码使用JavaScript中的2个对象数组并进行比较并合并内容,返回第一个数组中的所有对象,以及第二个对象中ID不在第一个数组中的所有对象。 / p>
但是对于那些来自第二个数组的项目,我想修改它在新数组中的条目,使其仅包含某些属性(例如id和make),并添加一个新的占位符属性(例如,键入:“ car ”)。我相信它将使用map函数,但是我似乎无法使其正常工作。
var cars1 = [
{id: 1, make: "Ford", model: "F150", year: 2002},
{id: 3, make: "Chevy", model: "Tahoe", year: 2003},
];
var cars2 = [
{id: 2, make: "Kia", model: "Optima", year: 2001},
{id: 4, make: "Nissan", model: "Sentra", year: 1982},
];
const cars1IDs = new Set(cars1.map(({ id }) => id));
const combined = [
...cars1,
...cars2.filter(({ id }) => !cars1IDs.has(id))
.map(cars2 => cars2.id)
];
combined.sort(({ id: aId }, {id: bId }) => aId - bId);
console.log(combined);
我希望组合的数组以以下内容结尾:
var combined = [
{id: 1, make: "Ford", model: "F150", year: 2002},
{id: 2, make: "Kia", type: "car"},
{id: 3, make: "Chevy", model: "Tahoe", year: 2003},
{id: 4, make: "Nissan", type: "car"},
];
但是它最终以:
var combined = [
{id: 1, make: "Ford", model: "F150", year: 2002},
{id: 3, make: "Chevy", model: "Tahoe", year: 2003},
2,
4
];
答案 0 :(得分:4)
在.map
中,应提取id
和make
属性,并返回一个对象,该对象仅包含这些属性以及type
的{{1}}:
car
答案 1 :(得分:0)
您应该更改地图功能 这是代码。仅有car2的地图功能正在更改
var cars1 = [
{ id: 1, make: "Ford", model: "F150", year: 2002 },
{ id: 3, make: "Chevy", model: "Tahoe", year: 2003 }
];
var cars2 = [
{ id: 2, make: "Kia", model: "Optima", year: 2001 },
{ id: 4, make: "Nissan", model: "Sentra", year: 1982 }
];
const cars1IDs = new Set(cars1.map(({ id }) => id));
const combined = [
...cars1,
...cars2
.filter(({ id }) => !cars1IDs.has(id))
.map(car2 => {
//add new prop type to car
const tempCar2 = Object.assign(car2,{type:"car"});
//remove year and model
delete tempCar2.year
delete tempCar2.model
return tempCar2;
//Object.assign(car2, { id: car2.id });
})
];
combined.sort(({ id: aId }, { id: bId }) => aId - bId);
console.log(combined);