简体   繁体   English

将 arrays 转换为对象数组中的值(使用键!)

[英]Convert arrays to values (with keys!) in an array of objects

I scoured lots of posts for turning arrays into objects and it looks like there are A LOT of posts doing the reverse of what I'd like.我搜索了很多将 arrays 变成对象的帖子,看起来有很多帖子与我想要的相反。 If this is redundant with another post I'd like to see what the title is since I really struggled to find it!如果这与另一篇文章是多余的,我想看看标题是什么,因为我真的很难找到它!

I have two arrays:我有两个 arrays:

let x = [1,2,3]
let y = ["a", "b", "c"]

I want to create an array of objects with keys so that the resulting array looks like:我想创建一个带有键的对象数组,以便生成的数组如下所示:

data = [
  {x: 1, y: "a"},
  {x: 2, y: "b"},
  {x: 3, y: "c"}
]

I tried Object.assign and some other methods but am still struggling (and I'd also like to know what key words I should have used to search if this is already posted since I couldn't find it).我尝试了 Object.assign 和其他一些方法,但仍在苦苦挣扎(而且我还想知道如果由于找不到它已经发布,我应该使用哪些关键词进行搜索)。 Any help appreciated!任何帮助表示赞赏!

You could do that using map with index您可以使用带有索引的 map 来做到这一点

 let x = [1, 2, 3]; let y = ["a", "b", "c"]; const res = x.map((el, i) => ({ x: el, y: y[i] })); console.log(res);

Why not use a simple for loop为什么不使用简单的 for 循环

let x = [1,2,3]
let y = ["a", "b", "c"]

let data = [];

for(let i = 0 ; i < x.length; i++){
    data.push({x:x[i],y:y[i]});
}

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

相关问题 将对象数组转换为按值分组的数组数组 - Convert array of objects to array of arrays grouped by values 使用自定义键和值将JSON转换为对象数组 - Convert JSON to array of objects with custom keys and values 将值转换为 Javascript 中对象数组的键 - Convert values into keys for an array of objects in Javascript 如何将具有数组作为值的对象转换为对象数组 - How to convert an object with arrays as values to an array of objects JavaScript - 将对象的多个 arrays 转换为基于水平值的 arrays 数组 - JavaScript - Convert multiple arrays of an objects to horizonal values based array of arrays lodash将对象数组转换为键的单个数组和值的多个数组 - lodash convert array of objects to single array of keys and multiple array of values 获取值是数组的对象数组中的所有键 - Get all keys in array of objects whose values are arrays Javascript - 将数组数组转换为具有预填充值的对象数组 - Javascript - convert array of arrays into array of objects with prefilled values 如何使用另一个对象数组的键和 arrays 数组中的值来构造对象数组? - How to construct an array of objects by using the keys of another array of objects and values from the array of arrays? 将对象数组转换为仅具有值(无索引或键)的对象 - Convert array of objects into an object with only values (no index or keys)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM