1

I have an object items = {a:"arr", b:"brr", c: "3"}. I want to turn it into an array, but multiplied by c. So if items = {a:"arr", b:"brr", c: "3"} i want to get:

["arr brr","arr brr","arr brr"].

2 Answers 2

3

You can use Array.from() to generate an array with the length of the value of c:

const items = {a:"arr", b:"brr", c: "3" }

const result = Array.from(
  { length: +items.c }, 
  () => `${items.a} ${items.b}`
)

console.log(result)

Use Array.flatMap() with Array.from() to handle an array of objects:

const items = [{a:"arr", b:"brr", c: "3" },{a:"ann", b:"bnn", c: "1" }]

const result = items.flatMap(obj => Array.from(
  { length: +obj.c }, 
  () => `${obj.a} ${obj.b}`
))

console.log(result)

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

1 Comment

and if i have array of objects? [{a:"arr", b:"brr", c: "3" },{a:"ann", b:"bnn", c: "1" }] so i get ["arr brr","arr brr","arr brr","ann, bnn"]
0

Using Array constructor and fill() method can achieve with one line of code:

const items = {a:"arr", b:"brr", c: "3"}
const arr = new Array(+items.c).fill(`${items.a} ${items.b}`)

console.log(arr)

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.