给出以下对象数组:
var arrayOfObjs = [{
id: "d8eed6df-9f12-47d4-5b71-3352a92ebcf0",
typeID: 2
},
{
id : "270d8355-d8b6-49c4-48ac-97a44422c705",
typeID: 3
},
{
id : "sdks7878-d8b6-49c4-48ac-97a44422c705",
typeID: 4
}];
一堆Ints:
var arrayOfInts = [2, 4];
如果int数组与arrayOfObjects匹配,我如何比较两者并返回一个ID数组。
回报应该是:
var matchingIDs = [
"d8eed6df-9f12-47d4-5b71-3352a92ebcf0",
"sdks7878-d8b6-49c4-48ac-97a44422c705"
];
var missingIDs = ["270d8355-d8b6-49c4-48ac-97a44422c705"];
答案 0 :(得分:3)
使用array.prototype.filter
,array.prototype.includes
和array.prototype.map
var datas = [{
id: "d8eed6df-9f12-47d4-5b71-3352a92ebcf0",
typeID: 2
},
{
id : "270d8355-d8b6-49c4-48ac-97a44422c705",
typeID: 3
},
{
id : "sdks7878-d8b6-49c4-48ac-97a44422c705",
typeID: 4
}];
var arrayOfInts = [2, 4];
var matchingIDs = datas.filter(d => arrayOfInts.includes(d.typeID)).map(e => e.id);
var missingIDs= datas.filter(d => !arrayOfInts.includes(d.typeID)).map(e => e.id);
console.log('matchingIDs: ', matchingIDs);
console.log('missingIDs: ', missingIDs);

答案 1 :(得分:1)
实现这一目标的方法很多,我选择了map \ filter用法,因为javascript是一种函数式语言。
const allItems = [{
id: "d8eed6df-9f12-47d4-5b71-3352a92ebcf0",
typeID: 2
},
{
id : "270d8355-d8b6-49c4-48ac-97a44422c705",
typeID: 3
},
{
id : "sdks7878-d8b6-49c4-48ac-97a44422c705",
typeID: 4
}];
const validIds = [2, 4];
const filteredItems = allItems
.filter(({typeID})=> validIds.includes(typeID))
.map(({id})=>id)
console.log(filteredItems)
答案 2 :(得分:0)
使用lodash,您可以使用包含_.keyBy()
,_.at()
和_.map()
的链来实现此目的:
var arrayOfObjs = [{"id":"d8eed6df-9f12-47d4-5b71-3352a92ebcf0","typeID":2},{"id":"270d8355-d8b6-49c4-48ac-97a44422c705","typeID":3},{"id":"sdks7878-d8b6-49c4-48ac-97a44422c705","typeID":4}];
var arrayOfInts = [2, 4];
var result = _(arrayOfObjs)
.keyBy('typeID') // get a dictionary of objects by their type ids
.at(arrayOfInts) // get the objects that matches the array of ints
.map('id') // map each object to the id
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>