0

I am wondering if there is a way to dynamically add objects to an array of objects based on a value? For example, I have an array of objects:

[
    {category:A, num:5}, 
    {category:B, num:2}
] 

I want to create another array of objects where objects would be the same, but repeated based on the value of num (so 5 times for category A and 2 times for category B) :

[
    {category:A, num:5, repeated:1},
    {category:A, num:5, repeated:2},
    {category:A, num:5, repeated:3},
    {category:A, num:5, repeated:4},
    {category:A, num:5, repeated:5},
    {category:B, num:2, repeated:1}, 
    {category:B, num:2, repeated:2}
]

I have tried map, forEach, for loop, but nothing worked. I am quite new to javascript, how some one could help!

3
  • 4
    Are you confusing java with javascript? Commented Sep 29, 2020 at 14:09
  • This Wikipedia page (en.wikipedia.org/wiki/Java_(programming_language) states: Not to be confused with JavaScript. Commented Sep 29, 2020 at 14:13
  • Ohh, just a mistake in the tag, thank you. Commented Sep 29, 2020 at 14:18

2 Answers 2

1

You can do this using a combination of flatMap and map:

var input = [
    {category:"A", num:5}, 
    {category:"B", num:2}
] ;

var result = input.flatMap(e => [...new Array(e.num)].map( (x,i) => ({
    category:e.category,
    num: e.num,
    repeated: i+1
})));
console.log(result);

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

Comments

1

You could do it using flatMap -

const repeat = ({ num = 0, ...t }) =>
  num === 0
    ? []
    : [ ...repeat({ ...t, num: num - 1 }), { ...t, num, repeated: num } ]

const input = 
  [ { category: "A", num: 5}, { category: "B", num: 2 } ]
  
const output =
  input.flatMap(repeat)
  
console.log(output)

Output -

[
  { category: "A", num: 1, repeated: 1 },
  { category: "A", num: 2, repeated: 2 },
  { category: "A", num: 3, repeated: 3 },
  { category: "A", num: 4, repeated: 4 },
  { category: "A", num: 5, repeated: 5 },
  { category: "B", num: 1, repeated: 1 },
  { category: "B", num: 2, repeated: 2 }
]

1 Comment

Thank you so much! Didnt know about flatMap, very useful.

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.