简体   繁体   English

如果键与数组值匹配,如何获取值

[英]how to get value if keys are matching with array values

I have written one array as below我写了一个数组如下

const OBJECT = {
    '3': 'History And Social Sciences',
    '5': 'Humanities',
    '8': 'Global Studies And Social Impact',
    '10': 'Sanskrit'
};

var rou=[3,5,8,10];

I want to fetch the field values when keys are matching with values.当键与值匹配时,我想获取字段值。 Does anyone have any idea on it?有没有人对此有任何想法?

map over rou and get the value from OBJECT of that key: map rou并从该键的OBJECT获取值:

 const OBJECT = { '3': 'History And Social Sciences', '5': 'Humanities', '8': 'Global Studies And Social Impact', '10': 'Sanskrit', }; var rou = [3, 5, 8, 10]; var values = rou.map(k => OBJECT[k]); console.log(values);

rou[0] is 3 , rou[1] is 5 and so on. rou[0] 是 3 ,rou[1] 是 5 等等。 What you want is to check if rou[0] that has the value 3, is key to you dictionary.您想要的是检查值为 3 的 rou[0] 是否是您字典的键。

You can access the value from the object like this您可以像这样从对象访问值

var value = OBJECT.rou[0] 

Iterate 'rou' array and for each value of it find the corresponding value in the OBJECT迭代 'rou' 数组,并为它的每个值在 OBJECT 中找到相应的值

   Iterator<String> it = jsonObject.keys(); 
   List<Integer> list=new ArrayList();
   while(it.hasNext()){
   int key = it.next(); 
   list.add(key);
   }

Loop over the object properties and compare if the key is found in arr by indexOf if found get the value of that key.循环遍历对象属性并通过indexOf比较键是否在 arr 中找到,如果找到,则获取该键的值。

 const OBJECT = {'3': 'History And Social Sciences','5': 'Humanities','8': 'Global Studies And Social Impact','10': 'Sanskrit','a': 'abc'}; var rou = [3, 5, 8, 10]; for (var property in OBJECT) { if (OBJECT.hasOwnProperty(property) && rou.indexOf(parseInt(property)) != -1) { console.log(OBJECT[property]); } }

You can also do it by iterating the array and if the element of array is present in the object get the value of that object您也可以通过迭代数组来实现,如果对象中存在数组元素,则获取该对象的值

 const OBJECT = {'3': 'History And Social Sciences','5': 'Humanities','8': 'Global Studies And Social Impact','10': 'Sanskrit','a': 'abc'}; var rou = [3, 5, 8, 10]; rou.forEach(function(element) { if (OBJECT[element] != undefined) { console.log(OBJECT[element]); } });

With ramdajs' pick , it's easier.使用ramdajs' pick ,它更容易。

R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1}

If you're interested, check its implementation如果您有兴趣,请检查其实现

 const OBJECT = { '3': 'History And Social Sciences', '5': 'Humanities', '8': 'Global Studies And Social Impact', '10': 'Sanskrit' }; var rou=[3,5,8,10]; var res = Object.keys(OBJECT).reduce((acc, cur) => rou.indexOf(parseInt(cur)) !== -1 ? (acc.push(OBJECT[cur]), acc) : acc, []) console.log(res)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM