0

I will try to explain myself better. I have a javascript object. for example:

const obj = {
 a: 1,
 b: 2,
 c: 3
};

What i need to return is let's say a <p> that will look like this:

<p>a 1</p>
<p>b 1</p>
<p>b 2</p>
<p>c 1</p>
<p>c 2</p>
<p>c 3</p>

I am trying to catch how many times a value is there inside a key. and based on that generate the result i displayed above.

I'm trying to do something like:

for (var k in obj) {
    if (obj.hasOwnProperty(k)) {
      return <p>{`key ${k} value ${obj[k]}`}</p>;
    }
  }
}

This return only 1 paragraph.. how can i initiate over those key values and generate those paragraphs like i displayed in the example? Thanks!

EDIT:

If it's easier, how can i convert obj into

newObj = [
 {
  name: a,
  number: 1
 },
 {
  name: b,
  number: 1
 },
 {
  name: b,
  number: 2
 },
 {
  name: c,
  number: 1
 },
 {
  name: c,
  number: 2
 },
 {
  name: c,
  number: 3
 }
];

I can then achieve the result i want with simple Map.

Ilanus
  • 6,690
  • 5
  • 13
  • 37
  • 2
    I don't think this is a dupe, the question is how to iterate over the values in an Object. –  Sep 09 '16 at 19:18
  • Guys would you at least read my question before making duplicate .. – Ilanus Sep 09 '16 at 19:20
  • `obj[k]` returns the number of paragraphs you want to make, so you would just iterate that number of times. Something to the effect `var paragraphs ='' ;for(var i = 0; i < obj[k]; i++){paragraphs += "

    {'key ${k} value i}

    ";}return paragraphs;`
    –  Sep 09 '16 at 19:22

1 Answers1

1

Quite easy with a small helper function times():

const times = (n, fn) => [...Array(n)].map((_, i) => fn(i));

const obj = {
 a: 1,
 b: 2,
 c: 3
};

let result = [];

Object.keys(obj).forEach(k => 
  times(obj[k], i => 
    result.push('<p>' + k + (i + 1) + '</p>')));

console.log(result);
                         
                         
                         
georg
  • 211,518
  • 52
  • 313
  • 390