简体   繁体   English

将一个数组与嵌套数组进行比较,并将值推送到 Javascript 中具有相同索引的新数组中

[英]Compare one array with a nested array and push value into a new array with same index in Javascript

I have 2 arrays我有 2 个数组

const arrayOne = [
 {
  id: '110'
 },
 {
  id: '202'
 },
 {
  id: '259'
 }
];

const arrayTwo = [
 {
  data: [
   {
     value: 'Alpha',
     id: '001'
    }
   ],
 {
  data: [
    {
     value: 'Bravo',
     id: '202'
    }
  ]
 }
];

I need to create a new array comparing arrayOne[idx].id with arrayTwo[idx].data[idx2].id我需要创建一个新数组,将arrayOne[idx].idarrayTwo[idx].data[idx2].id进行比较

Upon match, I need to create an array pushing value ( arrayTwo[idx].data[idx2].value ) to the new array against each index in arrayOne .匹配后,我需要针对arrayOne中的每个索引创建一个数组推送arrayTwo[idx].data[idx2].value )到新数组。

In this example, I would get newArr = [null, 'Bravo', null]在这个例子中,我会得到newArr = [null, 'Bravo', null]

What I have tried:我试过的:

arrayOne.map(item => ({
   ...item,
   result: arrayTwo.filter(itemTwo => item.data.map(x => x.id).includes(itemTwo.id))
}));

and also并且

const newArr = [];
arrayOne.map((item, idx) => {
   if (arrayTwo.filter(itemTwo => itemTwo.data?.map(x => x.id) === item.id)) {
     newArr.push(arrayTwo.data[idx].value);
   } else newArr.push(null);
 });
  • Use map to iterate over each element of arr1 and return a new array.使用map遍历arr1的每个元素并返回一个新数组。
  • Reassemble the data attribute array of each element in the arr2 array using map and flat使用mapflat重新组装arr2数组中每个元素的数据属性数组
  • When arr1 traverses, you can get the current element id , use filter to filter the combined data array, and return an element array that matches the current element id .arr1遍历时,可以得到当前元素id ,使用filter过滤合并后的数据数组,返回一个与当前元素id匹配的元素数组。
  • Based on the case where the id is not matched, use the optional chain operator to get the value.根据 id 不匹配的情况,使用可选链操作符获取值。
  • When returning返回时
    1. if you want to get the element array of the id and value attributes, use conditional (ternary) operator , when it doesn't match, return the original element, when it matches, use spread syntax , copy the current element attribute, and add the value attribute如果要获取 id 和 value 属性的元素数组,使用条件(三元)运算符,不匹配时返回原始元素,匹配时使用扩展语法,复制当前元素属性,并添加价值属性
    2. if you only want to get an array of matching results, just return the value, remember to use the optional chain operator to convert the unmatched value to null .如果只想获取匹配结果的数组,只需要返回值,记得使用可选的链运算符将不匹配的值转换为null

 const arr1 = [ { id: '110' }, { id: '202' }, { id: '259' } ]; const arr2 = [ { data: [{ value: 'Alpha', id: '001' }] }, { data: [{ value: 'Bravo', id: '202' }] } ]; const result1 = arr1.map(o1 => { const data = arr2.map(o2 => o2.data).flat(); const value = data.filter(o2 => o2.id === o1.id)[0]?.value; return value ? {...o1, value} : o1; }); const result2 = arr1.map(o1 => { const data = arr2.map(o2 => o2.data).flat(); const value = data.filter(o2 => o2.id === o1.id)[0]?.value; return value ?? null; }); [result1, result2].forEach(r => console.log(JSON.stringify(r)));

This seems difficult at first because of how arrayTwo is structured.起初这似乎很困难,因为arrayTwo的结构。 We can make our lives much easier by converting it into a dictionary, then we can just map arrayOne to get our results.我们可以通过将它转换成字典来使我们的生活更轻松,然后我们可以映射arrayOne来获得我们的结果。

 const arrayOne = [ {id: '110'}, {id: '202'}, {id: '259'} ]; const arrayTwo = [ {data: [{value: 'Alpha',id: '001'}]}, {data: [{value: 'Bravo',id: '202'}]} ]; const dict = {}; arrayTwo.forEach((obj) => { let key = obj.data[0].id let value = obj.data[0].value dict[key] = value } ) const result = arrayOne.map(obj => (dict[obj.id] || null)) console.log('Output: ', result) console.log('Dictionary:', dict)
This can also be done with Array.prototype.reduce() : 这也可以通过Array.prototype.reduce()来完成:

 const arrayOne = [ {id: '110'}, {id: '202'}, {id: '259'} ]; const arrayTwo = [ {data: [{value: 'Alpha',id: '001'}]}, {data: [{value: 'Bravo',id: '202'}]} ]; const dict = arrayTwo.reduce((output, obj) => { let key = obj.data[0].id let value = obj.data[0].value output[key] = value return output }, {}) // dict = {'001':'Alpha', '202': 'Bravo'} const result = arrayOne.map(obj => (dict[obj.id] || null)) console.log(result)

You can try this easy line of code :你可以试试这行简单的代码:

 const arrayOne = [{ id: '110' }, { id: '202' }, { id: '259' }]; const arrayTwo = [{ data: [{ value: 'Alpha', id: '001' }], }, { data: [{ value: 'Bravo', id: '202' }] }]; let result = arrayOne.map(el => { let found = arrayTwo.find(f => f.data.at(0)?.id == el.id)?.data.at(0)?.value; return { id: el.id, value: found ?? null}; }); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将一个数组与嵌套数组进行比较,并将值推送到 Javascript 中的新数组中 - Compare one array with a nested array and push value into a new array in Javascript Javascript 在数组索引上传播以将新项目“推送”到嵌套数组 - Javascript spread on array index to 'push' new item to nested array Javascript 比较索引与数组值 - Javascript Compare Index with Array Value 数组推送对JavaScript中的相同值使用相同的索引 - Array Push uses the same index for the same value in JavaScript Javascript 如何将新元素从初始数组推送到同一索引的 arrays 数组中的每个数组? - Javascript how to push a new element from an initial array to each array inside an array of arrays at the same index? 比较两个 arrays 并将相同的元素推送到一个数组中,将 rest 推送到另一个数组中的 javascript - Compare two arrays and push same element in one array and rest in other array in javascript JavaScript:在同一索引上推送具有多个值的数组 - JavaScript: Push Array with multiple values on same index 将数组推入嵌套数组JavaScript - Push array into Nested array javascript 在React挂钩中将新值推送到嵌套数组 - Push a new value to nested array in React hooks JavaScript 比较两个 arrays 并将在第二个数组中具有相同属性值的项目推送到第一个数组 - JavaScript compare two arrays and push items to the first array that have the same property value in the second array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM