简体   繁体   English

Javascript - 从两个 Arrays 创建嵌套对象数组

[英]Javascript - Create Nested Array of Objects From Two Arrays

Trying to create a single combined array of objects from two arrays:尝试从两个 arrays 创建一个对象组合数组:

let versions = [
          {
            version: "1609936394",
          },
          {
            version: "1609936409",
          }
]

and

let devices = [
  {
    download_device: "Box 1",
  },
  {
    download_device: "Box 2",
  },
  {
    download_device: "Box 3",
  },
  {
    download_device: "Box 4",
  }
]

The outcome I'm trying to achieve, albeit unsuccessfully, is having a separate entry for each download_device and version number combination, ie.尽管没有成功,但我试图达到的结果是每个 download_device 和版本号组合都有一个单独的条目,即。

[
    {
        download_device: "Box 1",
        version: "1609936394"
    },
    {
        download_device: "Box 2",
        version: "1609936394"
    },
    {
        download_device: "Box 3",
        version: "1609936394"
    },
    {
        download_device: "Box 4",
        version: "1609936394"
    },
    {
        download_device: "Box 1",
        version: "1609936409"
    }...

Any help would be greatly appreciated!任何帮助将不胜感激!

My current solution (only outputs the first version number):我当前的解决方案(只输出第一个版本号):

let data = devices.map((d, index) => {
                       versions.map((v, i) => {
                         v.device = devices[index].download_device,
                         d.version = versions[index].version
                         return v;
                       })
                     return d;
                })

The main issue with your approach is that you're trying to access invalid indexes.您的方法的主要问题是您试图访问无效索引。 As your devices array is longer than your versions array, you will reach indexes which don't exist within your versions array, causing an issue when you try and access a property on an index that doesn't exist.由于您的devices数组比您的versions数组长,您将到达versions数组中不存在的索引,当您尝试访问不存在的索引上的属性时会导致问题。

Instead, you can map over your versions array, and for each version map over your devices array (as you want to add the version to all devices).相反,您可以 map 在您的versions阵列上,并为每个版本 map 在您的设备阵列上(因为您想将版本添加到所有设备)。 When you map over your devices, you can grab the properties from each device, and spread them into a new object ( ...obj ) using the spread syntax .当您在设备上进行 map 时,您可以从每个设备中获取属性,并使用扩展语法将它们传播到新的 object ( ...obj ) 中。 In this new object, you can also add the current version property.在这个新的 object 中,您还可以添加当前version属性。 Since the inner .map() will return an array, you can change the outer .map() method to a .flatMap() which will flatten each array returned from the callback into one larger array result:由于内部.map()将返回一个数组,您可以将外部.map()方法更改为.flatMap() ,这会将回调返回的每个数组展平为一个更大的数组结果:

 const versions = [ { version: "1609936394", }, { version: "1609936409", } ]; const devices = [ { download_device: "Box 1", }, { download_device: "Box 2", }, { download_device: "Box 3", }, { download_device: "Box 4", } ]; const res = versions.flatMap(({version}) => devices.map(obj => ({...obj, version}))); console.log(res);

Build all combinations by first iterate over versions and inside version at each entry iterate over your devices.通过首先迭代版本和内部版本在每个条目上迭代您的设备来构建所有组合。

build a new Object Literal and push that Object literal to a result array.构建一个新的 Object 文字并将 Object 文字推送到结果数组。

 let versions = [{ version: "1609936394", }, { version: "1609936409", } ] let devices = [{ download_device: "Box 1", }, { download_device: "Box 2", }, { download_device: "Box 3", }, { download_device: "Box 4", } ] let res = []; versions.forEach((x) => { devices.forEach((y) => { let obj = { "version": x.version, "download_device": y.download_device }; res.push(obj); }); }) console.log(res);

You have two arrays of objects.您有两个 arrays 对象。 To create a single array that has each element of one with every element in the other.创建一个数组,其中一个元素的每个元素与另一个元素中的每个元素相结合。

A general solution that doesn't care about property names iterates over one array and creates copies of the other and combines the properties, eg:一个不关心属性名称的通用解决方案迭代一个数组并创建另一个数组的副本并组合属性,例如:

 let versions = [ {version: "1609936394"}, {version: "1609936409"} ]; let devices = [ {download_device: "Box 1"}, {download_device: "Box 2"}, {download_device: "Box 3"}, {download_device: "Box 4"} ] // Step by step version let result1 = versions.reduce((acc, ver) => { devices.forEach(device => { // Shallow copy device let o = {...device}; // Shallow copy ver onto o Object.assign(o, ver); // Add to accumulator acc.push(o); }); return acc; }, []); console.log(result1); // Concise version let result2 = versions.reduce((acc, ver) => ( devices.forEach(device => acc.push({...device, ...ver}) ), acc), []); console.log(result2);

Note these are shallow copies, and duplicate properties between the objects being combined aren't handled.请注意,这些是浅拷贝,不会处理正在组合的对象之间的重复属性。

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

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