1

I have two arrays as listed below. I'm trying to create a new array of objects by using the field key in array_1 and the values in 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.

Thanks,

4
  • You tried doing it yourself? Commented May 12, 2021 at 13:21
  • Yes, I did. My result was [ [{}] , [{}] ]. Commented May 12, 2021 at 13:23
  • 2
    Please include that code in your question. Commented May 12, 2021 at 13:24
  • Thanks for all of your help Commented May 12, 2021 at 13:53

4 Answers 4

1

One way to do it is to map() over the array_2 and in each iteration:

  1. Create a new object
  2. Iterate over the array_1 to fill the newly created 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.

and then return that object from the callback function of the map() method.

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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_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);

Comments

1

Explanation

You could create a function that creates a constructor based on the descriptions of your object's fields like this:

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:

const SampleConstructor = createConstructor(array_1)

And then, for each entry in array_2 you could apply your 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.

For example calling result[0].constructor == SampleConstructor will be true because SampleConstructor is the constructor that created the first result.

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)

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.