Home > database >  build array of json object while looping array of data
build array of json object while looping array of data

Time:05-05

I have an array const A=['string1','string2','string3'].

I want to achieve an object that has the following form:

const images = [
  { url: "string1" },
  { url: "string2" },
  { url: "string3" }
];

This is what I've tried:

const images = A.map((image) => {
  JSON.stringify({
    url: `/img/{image}`
  });
});

But the result is an array filled with undefined values.

CodePudding user response:

I do not understand why are you using JSON.stringify()?

The simplest solution:

const images = A.map((image) => ({
  url: `/img/${image}`
}))

The () that are wrapping the implicit return are mandatory since we're directly returning an object.

  • Related