0

I have data that looks like this returning from an api

var data =   {
        "entities": [
            {

                "documentbody": Base64String,
                "filename": "http-status-code-cheat-sheet1.png",
                "filesize": 204326,
               "mimetype": "image/png",

            },
             {

                "documentbody": null,
                "filename": "http-status-code-cheat-sheet2221.png",
                "filesize": 204326,
                "mimetype": "image/png",
            }
        ]
    }

I would like to create a new array that looks like this

var images = [ 
{  imgsrc:(documentBodyValue),imgDesc:(fileNameValue)},
{imgsrc:(documentBodyValue),imgDesc:(fileNameValue)}
]

I have tried using the map function let result = data.entities.map(a => a.filename); but this only returns the values into a new array. How can i create a new array with different keys but values from the original array?

0

3 Answers 3

4

Just return a new object from the map for each item.

let result = data.entities.map(a => ({imgsrc: a.documentbody, imgDesc: a.filename})); 
Sign up to request clarification or add additional context in comments.

1 Comment

I love javascript! This is so neat. Thank you for your response
3

Your attempt is almost correct. You can use {key: value, ...} syntax to map to an obj instead of values. E.g.:

var data = {
  "entities": [
    {

      "documentbody": 'Base64String',
      "filename": "http-status-code-cheat-sheet1.png",
      "filesize": 204326,
      "mimetype": "image/png",

    },
    {

      "documentbody": null,
      "filename": "http-status-code-cheat-sheet2221.png",
      "filesize": 204326,
      "mimetype": "image/png",
    }
  ]
};

let result = data.entities.map(a => ({imgsrc: a.documentbody, imgDesc: a.filename}));
console.log(result);

Comments

2
var images = []
data.entities.forEach(entry => {
    images.push({imgsrc: entry.documentbody, imgDesc: entry.filename})
})

1 Comment

[].map is specifically intended for this situation, there's no reason to reinvent the wheel using forEach and push

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.