Miguel Moura Miguel Moura - 3 months ago 12
AngularJS Question

Map object changing array of objects

On an Angular application I have the following object with an array of requirements:

var source = {
position: "xyz",
requirements: [
{ a: { code: "a1", name: "a1" }, b: { code: "b1", name: "b1" } },
{ a: { code: "a2", name: "a2" }, b: { code: "b2", name: "b2" } }
]
};


I need to create a copy of this object as follows:

var target = {
position: "xyz",
requirements: [
{ acode: "a1", bcode: "b1" },
{ acode: "a2", bcode: "b2" }
]
};


So only the 'a' codes and 'b' codes are picked ...

What would be the best way to map such an object?

Answer

You can use Object.create() to copy the object in this case. Then just map over the requirements.

var source = {
  position: "xyz",
  requirements: [
    { a: { code: "a1", name: "a1" }, b: { code: "b1", name: "b1" } },
    { a: { code: "a2", name: "a2" }, b: { code: "b2", name: "b2" } }
  ]
};

var copy = Object.create(source);
copy.requirements = copy.requirements.map(item => {
  return {acode: item.a.code, bcode: item.b.code}
});

console.log(copy);

Comments