简体   繁体   English

如何使用另一个对象数组的键和 arrays 数组中的值来构造对象数组?

[英]How to construct an array of objects by using the keys of another array of objects and values from the array of arrays?

I have two arrays as listed below.我有两个 arrays 如下所列。 I'm trying to create a new array of objects by using the field key in array_1 and the values in array_2.我试图通过使用array_1 中的field键和array_2 中的值来创建一个新的对象数组。

const result = []
array_1 = [{ name: "Color" , field: "color"}, {name: "Shape", field: "shape" }, { name: "Whatever", field: "whatever" }]

array_2 = [["green", "rectangular", "whatever1"], ["yellow", "circle", "whatever2"]]

The result should be:结果应该是:

console.log(result)
// [{color:"green", shape:"rectangular", whatever: "whatever1"}, 
//  { color:"yellow", shape: "circle", whatever:"whatever2"}]

I did this at my final trial:我在最后的审判中这样做了:

const rowObj = {}
const result = array.map((subarray) => subarray.map((cell, index) => {
      console.log(cell,index)
      rowObj[columns[index].field] = cell
      return rowObj
    }))

Basically, I was overwriting the same object.基本上,我正在覆盖相同的 object。

Thanks,谢谢,

You can use array.map to iterate both arrays and take advantage of Object.fromEntries to build new objects based on the order of array elements:您可以使用array.map来迭代 arrays 并利用Object.fromEntries根据数组元素的顺序构建新对象:

 array_1 = [{ name: "Color", field: "color"}, {name: "Shape", field: "shape" }, { name: "Whatever", field: "whatever" }] array_2 = [["green", "rectangular", "whatever1"], ["yellow", "circle", "whatever2"]] let result = array_2.map( x => Object.fromEntries( array_1.map((y,i) => ([y.field, x[i]])))) console.log(result);

One way to do it is to map() over the array_2 and in each iteration:一种方法是map()array_2并在每次迭代中:

  1. Create a new object新建 object
  2. Iterate over the array_1 to fill the newly created object.遍历array_1以填充新创建的 object。 You can use the index parameter of the forEach() method's callback function to get the field property from the objects inside array_1 .您可以使用forEach()方法的回调 function 的 index 参数从array_1中的对象获取field属性。

and then return that object from the callback function of the map() method.然后从map()方法的回调 function 中返回 object。

 const array_1 = [ { name: 'Color', field: 'color' }, { name: 'Shape', field: 'shape' }, { name: 'Whatever', field: 'whatever' }, ]; const array_2 = [ ['green', 'rectangular', 'whatever1'], ['yellow', 'circle', 'whatever2'], ]; const result = array_2.map(arr => { const o = {}; arr.forEach((str, idx) => { o[array_1[idx].field] = str; }); return o; }); console.log(result);

Explanation解释

You could create a function that creates a constructor based on the descriptions of your object's fields like this:您可以创建一个 function,它根据对象字段的描述创建一个构造函数,如下所示:

function createConstructor(fieldsDescriptor) {
  return function(fields) {
    fieldsDescriptor.forEach((descriptor, index) => {
      this[descriptor.field] = fields[index]
    })
  }
}

Then you could, for example, make a sampleConstructor that creates objects based on the field names of array_1:然后,例如,您可以创建一个基于 array_1 的字段名称创建对象的 sampleConstructor:

const SampleConstructor = createConstructor(array_1)

And then, for each entry in array_2 you could apply your SampleConstructor:然后,对于 array_2 中的每个条目,您可以应用您的 SampleConstructor:

const result = array_2.map(fields => new SampleConstructor(fields))

Motivation动机

Creating a dedicated constructor adds some clear semantics to your app, shows readers what you are doing and also stores constructor information in the created objects at runtime.创建专用的构造函数会为您的应用程序添加一些清晰的语义,向读者展示您在做什么,并在运行时将构造函数信息存储在创建的对象中。

When you later want to know which constructor made which objects you can just call object.constructor and use this information to determine what kind of objects they are.当您以后想知道哪个构造函数生成了哪些对象时,您可以调用object.constructor并使用此信息来确定它们是什么类型的对象。

For example calling result[0].constructor == SampleConstructor will be true because SampleConstructor is the constructor that created the first result.例如调用result[0].constructor == SampleConstructor将是真的,因为 SampleConstructor 是创建第一个结果的构造函数。

Demo演示

Here is a full demo这是一个完整的演示

 const array_1 = [{ name: "Color", field: "color"}, {name: "Shape", field: "shape" }, { name: "Whatever", field: "whatever" }] const array_2 = [["green", "rectangular", "whatever1"], ["yellow", "circle", "whatever2"]] function createConstructor(fieldsDescriptor) { return function(fields) { fieldsDescriptor.forEach((descriptor, index) => { this[descriptor.field] = fields[index] }) } } const SampleConstructor = createConstructor(array_1) const results = array_2.map(fields => new SampleConstructor(fields)) console.log(results) const EmptyConstructor = createConstructor([]) console.log(results[0].constructor == SampleConstructor) console.log(results[0].constructor == EmptyConstructor)

You can try this你可以试试这个

array_1 = [
      { name: 'Color', field: 'color' },
      { name: 'Shape', field: 'shape' },
      { name: 'Whatever', field: 'whatever' }
    ];
    
    array_2 = [
      ['green', 'rectangular', 'whatever1'],
      ['yellow', 'circle', 'whatever2']
    ];
    
    const keys = array_1.map(item => item.field);
    
    const output = [];
    array_2.forEach(item => {
      const temp = {};
      for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        const value = item[i];
        temp[key] = value;
      }
      output.push(temp);
    });
    
    console.log(output);

暂无
暂无

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

相关问题 如何使用父对象数组中子对象数组的唯一值有效地构造新对象数组 - How to efficiently construct new object array using unique values from arrays of children inside an array of parent objects 使用另一个对象数组和一个对象构造一个对象数组 - Construct an array of objects using another array of objects and a single object 将 arrays 转换为对象数组中的值(使用键!) - Convert arrays to values (with keys!) in an array of objects 从另一个数组中排序对象键数组 - sorting the array of objects keys from another array 如何从一个对象数组中获取值到另一个对象数组中 - How to get values from one array of objects into another array of objects JavaScript 如何将对象数组中的值获取到数组数组中,以便每个子数组对来自类似键的值进行分组? - JavaScript How to get values from an array of objects into array of arrays so that each sub-array groups values from like keys? 如何使用 javascript 从对象数组中执行添加相同键的对象值并返回唯一对象? - How to perform addition of same keys' values of objects and return unique objects from array of objects using javascript? 如何从对象数组中获取具有特定键的唯一值的对象? - How to get objects with unique values for specific keys from array of objects? 使用另一个没有键的 id 数组从对象数组中查找值 - Find values from array of objects using another array of ids without keys 如何将 map 数组 arrays 转换为具有给定键数组的对象数组? - How to map an array of arrays into an array of objects with a given keys array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM