0

I am getting http response like this:

[
    {"id": "1", "name": "2", "value": "3", "any": "4"}
]

I want to convert it to something like this:

[
{
    "heading": "id"
    "content": "1"
},
{
    "heading": "name"
    "content": 2
},
{
    "heading": "value"
    "content": 3
},
{
    "heading": "any"
    "content": 4
}
]

I am using angular4.0.0 and I want to perform this in service method. How to achieve this result?

2
  • what have you tried to achieve this? Commented Feb 15, 2018 at 7:30
  • for and foreach loops Commented Feb 15, 2018 at 7:30

3 Answers 3

1

Here you go :

var arrayData = [
    {"id": "1", "name": "2", "value": "3", "any": "4"}
]

let finalArray = arrayData.map(el => {
  let returnArray = [];
  for(let key in el){
     returnArray.push({heading : key , content : el[key]})
  }
  return returnArray;
})

console.log(finalArray);

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

2 Comments

You return an array inside an array, it is not exactly the expected output. You must probably remove the map ;)
@sjahan , I have provided the solution is global , it will work for any number of result in arrayData , What you are saying was easy. :) , OP should understand code. :D
1

var response = [
    {"id": "1", "name": "2", "value": "3", "any": "4"}
];

var newJson = [];
response.forEach(function(val,index){
  Object.keys(val).forEach(function(data) {
      newJson.push({heading: data,content:val[data]})
  })
  console.log(newJson)
})

Comments

1

var responseData=[
    {"id": "1", "name": "2", "value": "3", "any": "4"}
];

var finalResult = [];
responseData.map(function(item){
var test = [];
var allKeys=Object.keys(item);
for(i=0;i<allKeys.length;i++)
{
finalResult.push({'heading':allKeys[i],'content':item[allKeys[i]]});
}
});

console.log(finalResult)

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.