[英]I am trying to retrieve result from 2 array
我正在嘗試根據第二個數組文本過濾第一個數組,但我不知道如何將計數過濾器從第二個數組更新到第一個數組。
第一個數組:
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.filter(o1 => secondArray.some(o2 => o1.text === o2.text));
我目前得到的結果:
var result=[
{text:"India",count:1,checked:true},
{text:"America",count:2,checked:false},
{text:"Uk",count:1,checked:true}
];
我試圖得到的結果如下:
var result=[
{text:"India",count:1,checked:true},
{text:"America",count:1,checked:false},
{text:"Uk",count:1,checked:true}
];
謝謝您的幫助!!!
您可以 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);
一個可能的解決方案如下
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)
此解決方案將合並兩個 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.