我正在尝试根据第二个数组文本过滤第一个数组,但是我没有得到如何将计数过滤器从第二个数组更新为第一个数组。
第一个数组:
resolve()
第二个数组:
const request = require('request');
const process = require('process');
const args = process.argv[2];
let offset = 0;
let flag = false;
const clientID = 'agdn5682y521syqhwkdrqmw7ho6v7d';
function getGameInfo(args, offset, clientID){
return new Promise(function(resolve, reject){
const options = {
method: 'GET',
url: `https://api.twitch.tv/kraken/streams/?game=${args}&limit=100&offset=${offset}`,
headers: {
'Client-ID': clientID,
'Accept': 'application / vnd.twitchtv.v5 + json'
}
}
request(options, function (err, response, body) {
if (err) return reject(err);
try {
resolve(JSON.parse(body));
} catch(e) {
reject(e);
}
});
});
}
getGameInfo("pubg", offset, clientID).then(function(val) {
console.log(val);
}).catch(function(err) {
console.log(err);
});
代码:
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));
感谢您的帮助!
答案 0 :(得分:1)
您可以映射第一个数组,然后从第二个数组中选择计数
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);
答案 1 :(得分:1)
可能的解决方案如下
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)
答案 2 :(得分:0)
此解决方案将合并两个数组以获得期望的结果(从答案中推论得出)
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);