0

This is my json:

{
    "senderName": "ifelse",
    "message": "Hi",
    "groups": [
    {
        "id": 14,
        "groupname": "Angular",
        "contactgroups": [
        {
            "id": 1,
            "contact": {
                "id": 1,
                "gsm": "123456789"
            }
        },
        {
            "id": 3,
            "contact": {
                "id": 2,
                "gsm": "111111111"
            }
        }],
        "select": true
    }],
    "draftData": {
        "contacts": [
        ]
    }
}

How to make the above json into:

[{phoneno: 123456789; sender: ifelse ; message: Hi},{phoneno: 11111111; sender: ifelse ; message: Hi}]

I want to take phoneno data from gsm object key

Which is best method to do this? for or forEach or anyother?

2
  • 1
    there is only one record like this or there are multiple records like this on your JSON? Commented Dec 18, 2017 at 9:23
  • 3
    I need for this exact json object :) Commented Dec 18, 2017 at 9:23

1 Answer 1

3

I guess, this is what you want. Use map to convert contactgroups to new array with phoneno.

var data = {
  "senderName": "ifelse",
  "message": "Hi",
  "groups": [{
    "id": 14,
    "groupname": "Angular",
    "contactgroups": [{
        "id": 1,
        "contact": {
          "id": 1,
          "gsm": "123456789"
        }
      },
      {
        "id": 3,
        "contact": {
          "id": 2,
          "gsm": "111111111"
        }
      }
    ],
    "select": true
  }],
  "draftData": {
    "contacts": []
  }
}

var result = data.groups[0].contactgroups.map(i => {
  return {
    phoneno: i.contact.gsm,
    sender: data.senderName,
    message: data.message
  }
})

console.log(result);

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

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.