Skip to content
Advertisement

build array of json object while looping array of data

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement