[英]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
并在每次迭代中:
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);
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))
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 是创建第一个结果的构造函数。
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.