1

I have an object like this:

{
  "PAV-001": {
    "09SGH6eBNbRpFw9WnHdQO1mYcku1": {},
    "09SGH6eBNbRpFw9WnHdQO1mYcku2": {},
    "09SGH6eBNbRpFw9WnHdQO1mYcku4": {},
    "09SGH6eBNbRpFw9WnHdQO1mYcku5": {}
  },
  "P-001": {
    "09SGH6eBNbRpFw9WnHdQO1mYcku1": {}
  },
  "PAV-002": {
    "09SGH6eBNbRpFw9WnHdQO1mYcku1": {},
    "09SGH6eBNbRpFw9WnHdQO1mYcku3": {},
    "09SGH6eBNbRpFw9WnHdQO1mYcku4": {},
    "09SGH6eBNbRpFw9WnHdQO1mYcku6": {}
  }
}

I want to store PAV-001's values(like:"09SGH6eBNbRpFw9WnHdQO1mYcku1" these) into an array, I tried: arr1.push(Object.keys(data[value])) But it doesn't work, how to address this issue? Thanks!

  • Does this answer your question? [push multiple elements to array](https://stackoverflow.com/questions/14723848/push-multiple-elements-to-array) – HeySora Mar 20 '21 at 11:02
  • Could you please also add full example of arr1.push ... method that you have tried? – HDallakyan Mar 20 '21 at 19:08

3 Answers3

1

You can spread the the array obtained by Object.keys method and pass that to push method of the array like

arr1.push(...Object.keys(data[value]));

or you can use Array.prototype.concat method and assign the value back to the array like

arr1 = arr1.concat(Object.keys(data[value])); 
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Thanks! It works now, but can I ask why does the spread syntax work? Or what does it do for this? –  Mar 20 '21 at 11:19
  • Spread syntax usage in this will pass the arguments to push as comma separated values rather than an array – Shubham Khatri Mar 20 '21 at 11:38
0

For values of a single key :

const object = {
    "PAV-001": {
        "09SGH6eBNbRpFw9WnHdQO1mYcku1": {},
        "09SGH6eBNbRpFw9WnHdQO1mYcku2": {},
        "09SGH6eBNbRpFw9WnHdQO1mYcku4": {},
        "09SGH6eBNbRpFw9WnHdQO1mYcku5": {}
    },
}

let myArray = []
Object.keys(object["PAV-001"]).forEach(key => myArray.push(key))

Or for the all values of all keys of object

Object.keys(object).forEach(_object => Object.keys(object[_object]).forEach(key => myArray.push(key)))
Momo
  • 794
  • 2
  • 7
  • 17
0

Perhaps, you can use Object.keys() which returns an array whose elements are strings. then just use map to map each key as a value to an array.

    const obj = {
        "PAV-001": {
          "09SGH6eBNbRpFw9WnHdQO1mYcku1": {},
          "09SGH6eBNbRpFw9WnHdQO1mYcku2": {},
          "09SGH6eBNbRpFw9WnHdQO1mYcku4": {},
          "09SGH6eBNbRpFw9WnHdQO1mYcku5": {}
        },
        "P-001": {
          "09SGH6eBNbRpFw9WnHdQO1mYcku1": {}
       },
       "PAV-002": {
          "09SGH6eBNbRpFw9WnHdQO1mYcku1": {},
          "09SGH6eBNbRpFw9WnHdQO1mYcku3": {},
          "09SGH6eBNbRpFw9WnHdQO1mYcku4": {},
          "09SGH6eBNbRpFw9WnHdQO1mYcku6": {}
       }
}

var arr = Object.keys(obj["PAV-001"]).map((key) => key);
console.log(arr)
Ran Turner
  • 14,906
  • 5
  • 47
  • 53