skip to Main Content

I have an array that contains several elements after that I created an object in which I passed this array as a value but it passed all the values as a single string.

var cars = ["Saab", "Volvo", "BMW"];
console.log(cars);
var test = Object.assign({}, cars);
console.log(test);

var anv = {
new1 : test,
id : "1.K"
}
console.log(anv);

The Output we are getting is this
enter image description here

But output we require after passing the array inside object

0:{id:"1.R", new1:"Saab"}
1:{id:"1.R", new1:"Volvo"}
2:{id:"1.R", new1:"BMW"}

I have tried the object assign method but not works for me

2

Answers


  1. Use the .map function to create an object for each item in the list

    const cars = ["Saab", "Volvo", "BMW"];
    
    const anv = cars.map(
      car => ({
        id: "1.K",
        car: car
      })
    )
    
    console.log(anv);
    Login or Signup to reply.
  2. Instead of using Object.assign at the beginning, you can first create the array of your desired output and then use Object.assign.

    Here is a demo-

    var cars = ["Saab", "Volvo", "BMW"];
    var anv = [];
    
    cars.forEach(item => {
      anv.push({
        new1: item,
        id: "1.K"
      })
    })
    
    var result = Object.assign({}, anv)
    console.log(result)

    Please let me know if I didn’t get your use case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search