Mark Lenon
Mark Lenon

Reputation: 13

Creating object based on array of objects

I want to use this array of objects:

[
{ car: "bmw", model: "e46", price: "1000" },
{ car: "bmw", model: "e52", price: "2000" },
{ car: "bmw", model: "X5", price: "4000" },
{ car: "bmw", model: "X3", price: "4500" },
{ car: "audi", model: "A3", price: "1500"},
{ car: "audi", model: "A4", price: "2500"},
{ car: "audi", model: "TT", price: "2800"},
{ car: "audi", model: "A8", price: "3500"}
]

and transform it to this:

let cars = { 
  bmw: {
    e46: "1000",
    e52: "2000",
    X5: "4000"
  },
  audi: {
    A3: "1500",
    A4: "2500",
    TT: "2800",
    A8: "3500"
  }
}

This is my code:

let obj = {};
function order(arr) {
  arr.forEach((e) => {
    obj[e.car] = {
      [e.model]: e.price
    }
  });
}

And its returning only last data in desired format. How can I achieve this?

Upvotes: 1

Views: 49

Answers (2)

Samudra Deka
Samudra Deka

Reputation: 101

This is an alternative giving you the desired result. You can try this..

var objsource=[
{ car: "bmw", model: "e46", price: "1000" },
{ car: "bmw", model: "e52", price: "2000" },
{ car: "bmw", model: "X5", price: "4000" },
{ car: "bmw", model: "e46", price: "1000" },
{ car: "audi", model: "A3", price: "1500"},
{ car: "audi", model: "A4", price: "2500"},
{ car: "audi", model: "TT", price: "2800"},
{ car: "audi", model: "A8", price: "3500"}
];

var car={};
var model={};
objsource.forEach(function(objs){
  if(!car.hasOwnProperty(objs.car)){
    car[objs.car]="";
  }
});
Object.keys(car).forEach(function(cars){
  objsource.forEach(function(objs){
    if(cars==objs.car){
      model[objs.model]=objs.price;
      car[cars]=model;
    }
  });
  model={};
})
 console.log(car);

Upvotes: 0

Musa
Musa

Reputation: 97672

You're assigning obj[e.car] every iteration, you should be adding an item every iteration

var arr = [
    { car: "bmw", model: "e46", price: "1000" },
    { car: "bmw", model: "e52", price: "2000" },
    { car: "bmw", model: "X5", price: "4000" },
    { car: "bmw", model: "e46", price: "1000" },
    { car: "audi", model: "A3", price: "1500"},
    { car: "audi", model: "A4", price: "2500"},
    { car: "audi", model: "TT", price: "2800"},
    { car: "audi", model: "A8", price: "3500"}
];
let obj = {};
function order(arr) {
    arr.forEach((e) => {
        if (!obj[e.car]){
            obj[e.car] = {};
        }
        obj[e.car][e.model] = e.price;
        
    });
}
order(arr);
console.log(obj);

Upvotes: 2

Related Questions