简体   繁体   English

如何从两个单独的数组创建具有两个键/值对的对象

[英]How to create an object with two key/value pairs from two separate arrays

I've got to separate arrays that I am wanting to combine and create an object with two distinct key / value pairs.我必须分离我想要组合的数组并创建一个具有两个不同键/值对的对象。 Is there anyway to create a single object with two key/value pairs from these two arrays?有没有办法用这两个数组中的两个键/值对创建一个对象? Structure and example of object I'm trying to create are below.我试图创建的对象的结构和示例如下。

My arrays are structured as follows:我的数组结构如下:

formLabel Array表单标签数组

const labelNames = this.state.formLabels;
*Output*
0: "Name"
1: "Prefix"
2: "First"
3: "Middle"
4: "Last"
5: "Suffix"
6: "Company Name"
7: "Email"
8: "Date Submitted"
9: "Lead Source"
10: "Owner Name"
11: "Owner Email"

formKeys Array表单键数组

const labelKeys = this.state.formKeys;
*Output*
0: "1"
1: "1.2"
2: "1.3"
3: "1.4"
4: "1.6"
5: "1.8"
6: "4"
7: "5"
8: "6"
9: "7"
10: "8"
11: "9"

How can I go about creating an object like such?我该如何去创建这样的对象?

0: {id: "LABEL KEY WOULD GO HERE", label: "LABEL NAME WOULD GO HERE"}
1: {id: "LABEL KEY WOULD GO HERE", label: "LABEL NAME WOULD GO HERE"}
... etc

As long as you have parallel arrays, you can map one of the arrays to a list of objects containing the current key and label (by index).只要您有并行数组,就可以将其中一个数组映射到包含当前键和标签(按索引)的对象列表。

 const labelNames = [ "Name" , "Prefix" , "First" , "Middle" , "Last" , "Suffix" , "Company Name" , "Email" , "Date Submitted" , "Lead Source" , "Owner Name" , "Owner Email" ]; const labelKeys = [ "1" , "1.2" , "1.3" , "1.4" , "1.6" , "1.8" , "4" , "5" , "6" , "7" , "8" , "9" ]; const res = labelKeys.map((key, idx) => ({ id: key, label: labelNames[idx] })); console.log(res);
 .as-console-wrapper { top: 0; max-height: 100% !important; }

You could create a reusable function as well:你也可以创建一个可重用的函数:

 const labelNames = [ "Name" , "Prefix" , "First" , "Middle" , "Last" , "Suffix" , "Company Name" , "Email" , "Date Submitted" , "Lead Source" , "Owner Name" , "Owner Email" ]; const labelKeys = [ "1" , "1.2" , "1.3" , "1.4" , "1.6" , "1.8" , "4" , "5" , "6" , "7" , "8" , "9" ]; const zip = (fn, ...arr) => arr[0].map((_, i) => fn(...arr.map(v => v[i]))); console.log(zip((id, label) => ({ id, label }), labelKeys, labelNames));
 .as-console-wrapper { top: 0; max-height: 100% !important; }

From what I can see in this question my best guess is this:从我在这个问题中看到的,我最好的猜测是:

 const labelNames = [ "Name", "Prefix", "First", "Middle", "Last", "Suffix", "Company Name", "Email", "Date Submitted", "Lead Source", "Owner Name", "Owner Email", ]; const labelKeys = [ "1", "1.2", "1.3", "1.4", "1.6", "1.8", "4", "5", "6", "7", "8", "9", ]; const newArrayWithObjects = labelNames.map((label,i) => ({ label, id: labelKeys[i] })); console.log(newArrayWithObjects);

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

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