0

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?

1
  • 1
    .map(x => {acode: x.a.code, bcode: x.b.code}) Commented Aug 29, 2016 at 15:23

2 Answers 2

3

You can use Object.assign() 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.assign({}, source);
copy.requirements = copy.requirements.map(item => {
  return {acode: item.a.code, bcode: item.b.code}
});

console.log(source);
console.log(copy);

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

6 Comments

I need to create a copy of source, e.g., target with the new format. Not changing the source. This is I am sending target to an API in the required format but not wanting to change the format that the client is using.
@MiguelMoura, sorry I missed that case. I've updated the answer to "copy" the original object.
using simply "var copy = source" would not make the same as Object.create?
Nope, doing var copy = source will not work because copy would then point to the same piece of memory as source. Which means that any changes to copy would be reflected in source.
Object.create() doesn't make copies, you probably want Object.assign({}, source).
|
0

You can simply loop around and do this

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 target ={};
var innerArray = [];
for(var key in source) {
  if (source.hasOwnProperty(key)) {
    if(typeof source[key] === 'string') {
       target[key] = source[key];   
    } else {
      for(var i = 0; i < source[key].length; i++) {
        var temp = {};
        temp.acode = source[key][i].a.code;
        temp.bcode = source[key][i].b.code;
        innerArray.push(temp);
      }
      target[key] = innerArray;    
    }
  }
}

console.log(target);

Here is the fiddle https://jsfiddle.net/Refatrafi/Lgryf2kv/12/

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.