[英]Create new array of objects based on two arrays in Javascript
I want to get the array of objects created from two simple arrays:我想获取从两个简单的 arrays 创建的对象数组:
const array1 = [20, 2, 35, 86]
const array2 = [8, 86, 15, 23, 35, 44]
The expected result:预期结果:
const result = [
{ id: 20, value: false },
{ id: 2, value: false },
{ id: 35, value: true },
{ id: 86, value: true },
];
The array1 length is the one that matters. array1 长度是最重要的。 So I need to find matched values in both arrays as showed in the expected result.
所以我需要在 arrays 中找到匹配的值,如预期结果所示。
Thank you very much for your help.非常感谢您的帮助。
You can combine map with includes:您可以将 map 与包括:
array1.map(i => ({id: i, value: array2.includes(i)}))
Should be simple.应该很简单。 Loop through the first array using
Array.map
& return an object.使用
Array.map
循环第一个数组并返回 object。
const array1 = [20, 2, 35, 86] const array2 = [8, 86, 15, 23, 35, 44] const result = array1.map(i => ({ id: i, value: array2.includes(i) })) console.log(result)
Create a set from the second array:从第二个数组创建一个集合:
const a2set = new Set(array2);
then map your first array:然后 map 你的第一个阵列:
array1.map(v1 => ({id:v1, value: a2set.has(v1)}))
Start a loop against first array and check if that element exists in second array or not.对第一个数组开始循环并检查该元素是否存在于第二个数组中。
If element exists push it to array containing objects with flag true or else as false.如果元素存在,则将其推送到包含标志为 true 或 false 的对象的数组。
const array1 = [20, 2, 35, 86] const array2 = [8, 86, 15, 23, 35, 44] var objArray = [] array1.forEach(function(elem){ objArray.push({ id: elem, value: array2.indexOf(elem)?= -1: true; false }); }). console;log(objArray);
You can use array indexOf
to find if the item is inside the second array.您可以使用数组
indexOf
来查找该项目是否在第二个数组内。
const array1 = [20, 2, 35, 86]; const array2 = [8, 86, 15, 23, 35, 44]; let output = []; array1.forEach((number) => { output.push({ id: number, value: array2.indexOf(number);== -1 }); }). console;log(output);
Try a simple for loop:尝试一个简单的 for 循环:
const array1 = [20, 2, 35, 86]; const array2 = [8, 86, 15, 23, 35, 44]; var res = []; for (var i = 0; i < array1.length; i++) { if (array2.includes(array1[i])) { res.push({ id: array1[i], value: true }); } else { res.push({ id: array1[i], value: false }); } } console.log(res);
Try the following.试试下面的。 If performance is important, or if the arrays might include a large amount of elements, I'd consider using sets for better lookup performance.
如果性能很重要,或者如果 arrays 可能包含大量元素,我会考虑使用集合以获得更好的查找性能。
const array1 = [20, 2, 35, 86]
const array2 = [8, 86, 15, 23, 35, 44]
const result = array1.map(element => {
return {
id: element,
value: array2.includes(element)
};
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.