0

Now I'm trying to add photos in my app.

For example, if there is one picture, the key is img_no_1, and the value is getting through the backend.

if can put up to 10 pictures, how can make img_no + number(The number of images.) according to the number of pictures?

I want to make a Array like imageList.

If there are five pictures,

const image_no = [145, 331, 392, 2, 39];
const imageList = [];


--------------------------------------------------------
imageList = [{
             img_no_1: 145,
             img_no_2: 331,
             img_no_3: 392,
             img_no_4: 2,
             img_no_5: 39
     }];

Thanks for your attention.

1
  • I would suggest using map and then Object.fromEntries. Commented Mar 9, 2022 at 10:13

1 Answer 1

2

Here is a very naive example using map and then Object.fromEntries:

  1. use map to return an array of array values in the shape ["key", "value"]
  2. Convert this array of arrays into an object using Object.fromEntries

const image_no = [145, 331, 392, 2, 39];
const imageList = [Object.fromEntries(
  image_no.map((num, i) => [
    `img_no_${i+1}`,
    num
  ])
)];

console.log(imageList)

If image_no is an array of image numbers:

const image_nos = [
  [145, 331, 392, 2, 39],
  [145, 331, 392, 2, 39]
];
const imageList = image_nos.map(image_no => Object.fromEntries(
  image_no.map((num, i) => [
    `img_no_${i+1}`,
    num
  ])
));

console.log(imageList)

Sign up to request clarification or add additional context in comments.

3 Comments

Cuz that array can be multiple as [{img_no_1: xx},{img_no_1: xx, img_no_2: xx}]
I've added an example for a multiple variant.
Nice. I was going to comment on a previous version of this answer to suggest using computed property names (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…), but I see my help is not needed here :)

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.