[英]I am trying to retrieve result from 2 array
i am trying to filter first array based on second array text, but i am not getting how to update the count filter to the first array from second array.我正在尝试根据第二个数组文本过滤第一个数组,但我不知道如何将计数过滤器从第二个数组更新到第一个数组。
First Array:第一个数组:
var firstArray =[{text:"India",count:1,checked:true},
{text:"America",count:2,checked:false},
{text:"Uk",count:1,checked:true}];
Second Array:第二个数组:
var secondArray=[
{text:"India",count:1,checked:false},
{text:"America",count:1,checked:false},
{text:"Uk",count:1,checked:false}
];
Code:代码:
var result=firstArray.filter(o1 => secondArray.some(o2 => o1.text === o2.text));
Result which i am currently getting:我目前得到的结果:
var result=[
{text:"India",count:1,checked:true},
{text:"America",count:2,checked:false},
{text:"Uk",count:1,checked:true}
];
Result which i am trying to get is below:我试图得到的结果如下:
var result=[
{text:"India",count:1,checked:true},
{text:"America",count:1,checked:false},
{text:"Uk",count:1,checked:true}
];
Thanks for the help!!!谢谢您的帮助!!!
You can map the first array and pick the count from second array like this您可以 map 第一个数组并像这样从第二个数组中选择计数
var firstArray = [
{ text: "India", count: 1, checked: true },
{ text: "America", count: 2, checked: false },
{ text: "Uk", count: 1, checked: true },
];
var secondArray = [
{ text: "India", count: 1, checked: false },
{ text: "America", count: 1, checked: false },
{ text: "Uk", count: 1, checked: false },
];
firstArray
.map((x) => {
const tmp = secondArray.find((y) => y.text === x.text);
return tmp ? { ...x, count: tmp.count } : null
})
.filter(Boolean);
A possible solution would like as below一个可能的解决方案如下
var firstArray = [{ text: "India", count: 1, checked: true }, { text: "America", count: 2, checked: false }, { text: "Uk", count: 1, checked: true } ]; var secondArray = [{ text: "India", count: 1, checked: false }, { text: "America", count: 1, checked: false }, { text: "Uk", count: 1, checked: false } ]; var result = firstArray.map(o1 => { const o2 = secondArray.find(o2 => o1.text === o2.text); if (;o2) return. return {..,o1: count. o2.count } });filter(o1 =>.!o1); console.log(result)
This solution will merge the two arrays to get the desidered result (as deduced from the answer)此解决方案将合并两个 arrays 以获得所需的结果(从答案中推断)
var firstArray =[{text:"India",count:1,checked:true}, {text:"America",count:2,checked:false}, {text:"Uk",count:1,checked:true}]; var secondArray=[ {text:"India",count:1,checked:false}, {text:"America",count:1,checked:false}, {text:"Uk",count:1,checked:false} ]; const newArray = firstArray.map((el1) => { let sameElList = secondArray.filter((el2) => el2.text === el1.text); let sameEl = sameElList.length > 0 && sameElList.pop(); if(;sameEl){ return el1. } el1.count = Math.min(el1,count. sameEl;count). el1.checked = el1.checked || sameEl;checked; return el1; }). console;log(newArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.