繁体   English   中英

在Javascript中从现有数组创建新数组

[英]Create new arrays from existing arrays in Javascript

我有数组:

const array_one = ["a", "b", "c"];

const array_two = ["d", "e"];

const array_Three = ["f", "g", "h"]

更多数组...

处理后返回结果:

[{"exp1":"a","exp2":"d","exp3":"f",},{"exp4":"a","exp5":"e","exp6":"g",},{"exp7":"a","exp8":"e","exp9":"h",},{"exp10":"b","exp11":"d","exp12":"f",}...,{"exp44":"c","exp45":"e","exp46":"h",}]

我举了一个比我遇到的更简单的例子,我想补充一下。

const array = [{values: ["a, "b", "c"]}, {values: ["d, "e", "f"]}, {values: ["g, "h", "i"]}...];

数组中的对象数量是动态的,目前我需要检查一下有多少个对象的数组,并在条件下重复......,我觉得不好,和性能有关,我想寻找其他方法简化代码,更容易理解。

exp 代码: if(array.length === 1){loop array[0].values}

if(array.length === 2){loop array[0].values { loop array[1].values }}

if(array.length === 3){loop array[0].values { loop array[1].values { loop array[2].values } }}

对象数量不固定,所以检查是否有其他不便......

您只需要三个基本的嵌套循环,只需将值推送到新数组

 const array_one = ["a", "b", "c"]; const array_two = ["d", "e"]; const array_three = ["f", "g", "h"]; const final_array = [] let c = 0; for (let one of array_one) { for (let two of array_two) { for (let three of array_three) { final_array.push({[`exp${++c}`]:one, [`exp${++c}`]:two, [`exp${++c}`]:three}) } } } console.log(final_array)

暂无
暂无

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

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