给出这样的数组:
a = [{id:1, name:'a'}, {id:2, name:'b'}, {id:3, name:'c'}, {id:4, name:'d'}, {id:5, name:'e'}];
b = ['a','d'];
c = [1,4];
我如何从a和b获得c?我想从名字中获取id。谢谢你。
答案 0 :(得分:2)
一种选择是使用.map
和.find
:
const a = [{id:1, name:'a'},{id:2, name:'b'}, {id:3, name:'c'},{id:4, name:'d'},{id:5, name:'e'}];
const b = ['a','d'];
const c = b.map(findName =>
a.find(({ name }) => name === findName)
.id
);
console.log(c);
您还可以将输入数组转换为按名称索引的对象,然后只对名称进行map
转换,以便每次都不需要.find
:
const a = [{id:1, name:'a'},{id:2, name:'b'}, {id:3, name:'c'},{id:4, name:'d'},{id:5, name:'e'}];
const b = ['a','d'];
const obj = a.reduce((accum, { id, name }) => {
accum[name] = id;
return accum;
}, {});
const c = b.map(name => obj[name]);
console.log(c);
答案 1 :(得分:2)
b.forEach(itemB => {
c.push(a.find(x=> x.name === itemB).id);
});
循环通过b数组并尝试find
数组a
中的c
,如果存在,请将id推入man crontab.5
答案 2 :(得分:1)
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while((t--)>0){
int n;
cin>>n;
int a[n];
string s="";
for(int i=0;i<n;i++){
cin>>a[i];
if(i==0){s+=to_string(a[i]); continue;}
string s1 = s+to_string(a[i]); //sX
string s2 = to_string(a[i])+s; //Xs
if(stoi(s1)>=stoi(s2))s=s1;
else s = s2;
}
cout<<s<<endl;
}
return 0;
}
答案 3 :(得分:0)
你可以这样使用
var d = a.filter((item)=>{
return b.indexOf(item.name) >= 0;
});
var c = d.map((item) => {
return item.id;
});
// Result = [1,4]
答案 4 :(得分:0)
请尝试这个
a = [ { id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
{ id: 4, name: 'd' },
{ id: 5, name: 'e' } ]
b = ['a','d'];
c = []
a.map(res => { if (b.includes(res.name)) { c.push(res.id) } });
alert(c)