简体   繁体   English

如何从一个数组和一个对象中.map()一个新的值数组?

[英]How do I .map() a new array of values from an array and an object?

let a1 = [1, 3, 5];
let a2 = {1: "a", 2: "b", 3: "c", 4: "d", 5: 2,}

// pass a function to map

const map1 = a1.map(? => ?);
console.log(map1);

// expected output: Array ["a", "c", 2]

I want the number in the array 1, 3, 5 to map to the values on the keys of a2 我希望数组1、3、5中的数字映射到a2的键上的值

What should "? => ?" “?=>”应该是什么? be for the desired result? 为预期的结果?

Edited 已编辑

My question is after reading the documentation Array.prototype.map() in MDN. 我的问题是在阅读MDN中的文档Array.prototype.map()之后。

My question is (not how to solve this) but to learn about the callback function in .map() : 我的问题是(不是解决方案),而是要了解.map()的回调函数:

let a1 = [1, 3, 5];
let a2 = {1: "a", 2: "b", 3: "c", 4: "d", 5: 2,}

// pass a function to map

const map1 = a1.map(a2, e => a2.value);
console.log(map1);

// expected output: Array ["a", "c", 2]

Here I wanted e in a1 to match a2 and return a2 in the map function, but it's clearly wrong but after Googling for examples I guess I just had to make a question about it and try not cause too much confusion. 在这里,我希望a1中的e匹配a2并在map函数中返回a2,但这显然是错误的,但是在使用谷歌搜索示例之后,我想我只需要提出一个问题,就不要造成太多的困惑。

Simply get the property from the object. 只需从对象获取属性。

 let a1 = [1, 3, 5]; let a2 = {1: "a", 2: "b", 3: "c", 4: "d", 5: 2,} // pass a function to map const map1 = a1.map(k => a2[k]); // -----------------^^^^^^^^^^---- console.log(map1); 

暂无
暂无

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

相关问题 如何将数组中的值映射到对象数组? - How to map values from an array to an array of Object? Map 数组 object 值到新数组 - Map array object values to new array 如何将数组 object 和 map 中的某些值的一部分从 AWS MongoDB 值分离到新数组中? - How to detach a part of some value inside a array object and map into new array from AWS MongoDB values? 如何将对象的值转换为数组? - How do I turn the values from an object into an array? 如何从对象中获取键和值并返回数组? - How do I get they keys and the values from the object and return an array? 如何从 Javascript 中的嵌套对象获取值数组 - How do I get array of values from a nested object in Javascript 如何在不更改接收新值的数组的 memory 地址的情况下将一个数组中的值加载到另一个数组中? - How do I load the values from one array, into another array, without changing the memory address of the array receiving the new values? 如何构造一个新的 object 数组,其中包含 JavaScript 中另一个对象数组中的一些已删除属性 - How do I construct a new array of object with some deleted properties from another array of objects in JavaScript Map 来自对象数组的新 object - Map new object from an array of objects 如何将对象属性值与数组值进行比较,然后将对象值替换为数组值? - How do I compare an object property values to the values of an array, and then replace the object values with the array values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM