简体   繁体   English

如何仅获取由键数组定义的对象中的值?

[英]How to get only the values in an object which are defined by an array of keys?

I have a simple object with several keys and values: 我有一个带有几个键和值的简单对象:

var obj = {SKA: 267, SKB: 30, SKC: 273, SKD: 900, SKE: 27, SKF: 3}

I also have a array with some keys: 我也有一些键的数组:

var keysArray = ["SKB", "SKF"]

I know that I can get all values by using Object.values(obj) . 我知道我可以使用Object.values(obj)获得所有值。 However I only need the values of the keys which are defined in the keysArray . 但是我只需要在keysArray中定义的键的值。 So, is there a simple way to get only the values of these keys and save them in a new array? 因此,是否有一种简单的方法来仅获取这些键的值并将其保存在新数组中?

I need the following result: 我需要以下结果:

var resultArray = [30, 3]

Many thanks. 非常感谢。

 keysArray.map(key => obj[key])
var resultArray =[];

keysArray.forEach(function(key){
    if(obj[key]){
        resultArray.push(obj[key]);
    }
});

I will recommend to use loop, like forEach on the keysArray instead of map on keysArray . 我会建议使用循环一样forEachkeysArray而不是mapkeysArray The reason for this is because map do not work for this: 这样做的原因是因为map对此不起作用:

 var obj = {SKA: 267, SKB: 30, SKC: 273, SKD: 900, SKE: 27, SKF: 3}; var keysArray = ["SKB", "SKF"]; var resultArray = []; keysArray.forEach((key)=>{ resultArray.push(obj[key]); }); console.log(resultArray); 

Here is why map do not fit with what you have asked: 这就是为什么map不符合您的要求的原因:

 var obj = {"SKA": 267, "SKB": 30, "SKC": 273, "SKD": 900, "SKE": 27, "SKF": 3}; var keysArray = ["SKB", "SKF"]; keysArray.map(key => obj[key]); console.log(keysArray); 

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

相关问题 如何从 object 中获取 object.key 数组(不是值,不是字符串,不仅是键)? - How do you get an array of object.key(not values, not string, not only keys) from an object? 如何从对象数组的多个键中获取所有值? - How to get all the values from multiple keys of an array of object? 如何从对象中获取键和值并返回数组? - How do I get they keys and the values from the object and return an array? 如何将数组值联接为键以获取jSON对象值 - How to join Array Values as keys to get jSON object value 如何从 object 数组中获取特定键值的总和 - How to get sum of specific keys values from array of object 如何使用动态键获取数组 object 值的总值 - how to get total value of array object values using dynamic keys 如何通过对象数组中嵌套的 object 键获取值 - how to get values by nested object keys in array of objects 获取对象数组中重复键的值 - Get values of duplicated keys in array of object 如何访问没有键的对象,只有值 javascript - How to access an object with no keys, only values javascript 我正在将 object 转换为该数组,但无法获得由数组中的键和值组成的预期数组,我错在哪里? - I am converting a object to this array, but cant get the expected array which would consist of Keys as well as values in the array, where am I wrong?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM