Javascript 比较对象值并返回新数组

Javascript 比较对象值并返回新数组,javascript,Javascript,我有两个阵列: const data = [ { type: 'type1', location: 23 }, { type: 'type2', location: 37 }, { type: 'type3', location: 61 }, { type: 'type4', location: 67 } ] const com = [ { name: "com1", location: 36 }, { name: "com2", location: 60 }

我有两个阵列:

const data = [ 
  { type: 'type1', location: 23 },
  { type: 'type2', location: 37 },
  { type: 'type3', location: 61 },
  { type: 'type4', location: 67 } 
]

const com = [ 
  { name: "com1", location: 36 },
  { name: "com2", location: 60 } 
]
我想测试数组
com
+1中的
locationComment
是否等于数组
data
中的
locationMethod
,如果是,那么我想得到如下结果:

const array = [
 {type: 'type2', name: "com1"},
 {type: 'type3', name: "com2"}
]
这是我的密码:

const result = data.map((x)=>{
  const arr = [];
  com.map((y)=>{
    if(x.location == y.location+1){
      arr.push({
        type: x.type,
        name: y.name,
        location: x.location
      })
    }
  })
  return arr;
});
这是我得到的输出:

[ [],
  [ { type: 'type2', name: 'com1', location: 37 } ],
  [ { type: 'type3', name: 'com2', location: 61 } ],
  [] ]

因为您不确定
com
数组中的每个元素是否都匹配,所以应该使用
reduce

const data=[
{type:'type1',位置:23},
{type:'type2',位置:37},
{type:'type3',位置:61},
{type:'type4',位置:67}
];
常数com=[
{名称:“com1”,地点:36},
{名称:“com2”,地点:60}
];
const output=com.reduce((a,{name,location})=>{
const found=data.find(item=>item.location==location+1);
如果(找到){
a、 推送({type:found.type,name});
}
返回a;
}, []);

控制台日志(输出)如果单行解决方案对您没有吸引力,那么下面的代码也应该使用.map()和.find()的组合


如果我想按索引搜索怎么办?类似于数据[index].find
data[index]
可能是匹配的对象,而不是数组,因此
.find
没有意义。你可以做
data[index].location===location+1
,如果位置匹配对我有效,它将计算为
true
,尽管这是一件非常奇怪的事情现在我明白了,这就是我需要的。。。谢谢你的帮助
const data = [ 
  { type: 'type1', location: 23 },
  { type: 'type2', location: 37 },
  { type: 'type3', location: 61 },
  { type: 'type4', location: 67 } 
]

const com = [ 
  { name: "com1", location: 36 },
  { name: "com2", location: 60 } 
]

// Final Array Output with merged properties
let finalArr = []

data.forEach(locationMethodObj => {

// Fetching the type
let finalObj = {
type: locationMethodObj.type
}

// Checking if a location match exists 
const foundObj = com.find(locationCommentObj => (locationCommentObj.location + 1) === 
locationMethodObj.location 
)

// If a match is found, then append name and push
if(foundObj){
finalObj.name = foundObj.name
finalArr.push(finalObj)
}
})

console.log(finalArr)