1

I am fetching API into my Express server which has several JSON key value pairs in one array. For Example:

[{
 "quality": "best",
 "url": "https://someurlhere.example/?someparameters"
},
{
 "quality": "medium",
 "url": "https://someurlhere1.example/?someparameters"
}]

And I want to create an array of JSON of that received data in this Format:

[{
"best": "https://someurlhere.example/?someparameters"
},
{
"medium": "https://someurlhere1.example/?someparameters"
}]

I have tried doing this by using for loop

for(let i=0; i < formats.length; i++){
   arr.push({
     `${formats[i].quality}` : `${formats[i].url}`
   })
}

But it didn't work for me.

Please help me in achieving this. Thanks in Advance :)

2 Answers 2

3

You could use the map function and create a new object from it.

For example:

let prevArr = [{
  "quality": "best",
  "url": "https://someurlhere.example/?someparameters"
}, {
  "quality": "medium",
  "url": "https://someurlhere1.example/?someparameters"
}]; // Replace with your array
let newArr = [];
let obj = {};

prevArr.map(function(x) {
  obj = {};
  obj[x["quality"]] = x.url;
  newArr.push(obj);
});
Sign up to request clarification or add additional context in comments.

1 Comment

It works as I want. Thanks :)
1
const input = [{
    "quality": "best",
    "url": "https://someurlhere.example/?someparameters"
}, {
    "quality": "medium",
    "url": "https://someurlhere1.example/?someparameters"
}];
const result = input.map((v, i) => {
    return {
        [v["quality"]]: v["url"]
    }
});
console.log(result)

1 Comment

You should also add some explanation of 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.