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!

2
  • Does this answer your question? push multiple elements to array Commented Mar 20, 2021 at 11:02
  • Could you please also add full example of arr1.push ... method that you have tried? Commented Mar 20, 2021 at 19:08

3 Answers 3

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])); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! It works now, but can I ask why does the spread syntax work? Or what does it do for this?
Spread syntax usage in this will pass the arguments to push as comma separated values rather than an array
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)))

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.