0

could you please help me to convert data in format like :

"tanks": [
      {
          "id": "1",
          "name": {
              "id": 1,
              "tor": "000"
          },
          "type": {
              "id": 1,
              "system": "CV-001"
          }
      }
  ]

into

"tanks":[
      {
          "type": 1,
          "name": 1 
      }
  ]

As you can see, type.id in the first array is the same as just type in the second. It is like I have to iterate through the array(as I have not only one Object in it) and left only needed fields in Objects, but I am stuck. Hope it is a little informative for you.

0

1 Answer 1

2

You can do this with a simple Array.map()

var obj = {
  tanks : [
    {
      "id": "1",
      "name": {
        "id": 1,
        "tor": "000"
      },
      "type": {
        "id": 1,
        "system": "CV-001"
      }
    },
    {
      "id": "2",
      "name": {
        "id": 2,
        "tor": "200"
      },
      "type": {
        "id": 2,
        "system": "CV-002"
      }
    }
  ] 
};

obj.tanks = obj.tanks.map(function(item) {
  return { 
    name : item.name.id,
    type : item.type.id
  };
});

console.log(obj);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

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

1 Comment

Thanks Dave, That's it!

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.