如何提取对象中指定键数组对应的取值并生成新数组?
Hey there! This is super straightforward with JavaScript's map() method—here's how you can get your desired result in one clean line:
var obj = {SKA: 267, SKB: 30, SKC: 273, SKD: 900, SKE: 27, SKF: 3}; var keysArray = ["SKB", "SKF"]; var resultArray = keysArray.map(key => obj[key]); console.log(resultArray); // Output: [30, 3]
How this works:
- The
map()function loops through each key in yourkeysArray. - For every key, we use bracket notation (
obj[key]) to fetch the corresponding value from the original object. - This returns a new array with the values in exactly the same order as your keys array—perfect for your use case!
Quick note on edge cases:
If any key in keysArray doesn't exist in obj, this will return undefined for that position in the result array. If you want to handle that (like filtering out missing keys), you could add a quick check:
var resultArray = keysArray.map(key => obj[key]).filter(val => val !== undefined);
But since your example uses keys that are definitely present in the object, the first solution is all you need.
内容的提问来源于stack exchange,提问作者Jaybruh
相关产品推荐
相关产品推荐

