0

I am working a demo react project, and got stuck to pick name and value of js object and push to an array. which I want to use for queryparams. The js objects looks as follow

const ingredient = [
    { salad: 0,  bacon: 0 },
    { cheese: 0, meat: 0  }
]

here I want the key and the value to push to an array. ex.

const arrays = []

I try this way and did not got it correct.

=> for (let name of ingredient){
arrays.push(name + ingredient[name])
 }
=> arrays
 (2) ["[object Object]undefined", "[object Object]undefined"]

how do I push only the name and value correctly so I will able to use them in the url?

thanks in advance for your help.

  • 7
    what are you expecting in `arrays`? – CoffeeTableEspresso Mar 15 '19 at 18:22
  • 1
    `for` iterates over the `indices` of the array, not the values. `name` is actually 0, 1, 2, 3, etc. See https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript –  Mar 15 '19 at 18:23
  • FYI: `for (let _ in ____)` is the syntax used to iterate over *objects*. Try it: `var foo = { a:1, b:2 }; for (let n in foo) { console.log(n); }` –  Mar 15 '19 at 18:27
  • Each object has two keys, so it's unclear what you want as a result. Do you want a flattened array of every key value concatenated together? – Taplar Mar 15 '19 at 18:28

3 Answers3

0

Try this:

ingredient.forEach((elem) => 
{
    for(key in elem)
    {
        arrays.push(`${key}, ${elem[key]}`);
    }
});
BugCatcherJoe
  • 487
  • 3
  • 17
0

First you have a struct problem: Instead of

const ingredient = [
    { salad: 0,  bacon: 0 },
    { cheese: 0, meat: 0  }
]

you should have

const ingredient = { salad: 0,  bacon: 0, cheese: 0, meat: 0  }

or

const ingredient = [{salade:0}, {bacon:0}, {cheese:0}, {meat:0}]

Let's say you keep only an object:

const ingredient = { salad: 2,  bacon: 3, cheese: 4, meat: 0  }

let toQuery = function(obj, is_str) {
  let arr = Object.keys(obj).reduce((acc, key) => { 
    acc.push(key+"="+obj[key]); 
    return acc 
  }, [])
  return is_str ? "?" + arr.join('&') : arr
}

console.log(toQuery(ingredient, false))
console.log(toQuery(ingredient, true))

Now make it works with your object (example, multi recipe)

const ingredient = [{ salad: 2,  bacon: 3}, {cheese: 4, meat: 0  }]


    let toQuery = function(obj, to_str) {
      let arr = []
      obj.forEach(o => {
        Object.keys(o).forEach(k => {
          arr.push(k+"="+o[k]) 
        })
      })
      return to_str ? "?" + arr.join('&') : arr
    }

    console.log(toQuery(ingredient, false))
    console.log(toQuery(ingredient, true))
Arthur
  • 4,870
  • 3
  • 32
  • 57
0

If name you mentioned is the key of object item. you can try this.

const ingredient = [
    { salad: 0,  bacon: 0 },
    { cheese: 0, meat: 0  }
]

const rs = ingredient.reduce((acc, e) =>{
  for(let key in e) {
    acc.push(`${key}: ${e[key]}`)
  }
  return acc
}, [])

console.log(rs)
bird
  • 1,872
  • 1
  • 15
  • 32