2

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"
     }
    ]
2
  • Have you tried anything in particular that you're having trouble with? Commented May 19, 2020 at 4:54
  • I alredy try it's work thanks sir. - @Phil Commented May 19, 2020 at 5:31

5 Answers 5

2

I'd use map() for this.

const objResult = result.map((item) => {
  return {
    type: item,
    image: item + '.jpg'
  };
});
Sign up to request clarification or add additional context in comments.

2 Comments

C'mon, you can make it way more terse than that ~ result.map(type => ({ type, image: `${type}.jpg` })) 😜
@Direak Yeah, no problem! If you find this answer useful, you can click that checkmark next to it, to flag your question as answered.
2

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; }

Comments

1

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);

Comments

1

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);

Comments

1

Use map

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

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.