how to change an array to json object in javascript

Viewed 49

I have an array like below

let result = ["a","b","c","d"]

then need to change like below how to do it Thank you for any help.

result  = [
     {
        type: "a",
        image: "a.jpg"
     },
     {
        type: "b",
        image: "b.jpg"
     },
     {
        type: "c",
        image: "c.jpg"
     },
     {
        type: "d",
        image: "d.jpg"
     }
    ]
5 Answers

I'd use map() for this.

const objResult = result.map((item) => {
  return {
    type: item,
    image: item + '.jpg'
  };
});

You can use array .map() method to return a new object with type & image properties like:

let result = ["a","b","c","d"]
result = result.map(r => ({type: r, image: `${r}.jpg`}))
console.log( result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can use Array.forEach() and Array.push() Array methods achieve the result:

let obj = [];
let result = ["a","b","c","d"]

result.forEach(function(el, i) {
  obj.push({
    type: el,
    image: `${el}.jpg`
  }) 
});

console.log(obj);

You would describe your function like this -

function convertResult(result){
    let ans = [];
    for(var i=0; i<result.length; i++){
        ans[i] = {'type': result[i], 'image': result[i]+'.jpg'};
    }
    return ans;
}

then you would call your function as this -

let result = ["a","b","c","d"]
let ans = convertResult(result);

Use map

let result = ["a","b","c","d"]
const map = result.map(x => ({"type":x,"image": x+".jpg"}));
console.log(map);

Related