Home > OS >  How to get a specific array of object of arrays in javascript
How to get a specific array of object of arrays in javascript

Time:03-03

Say I have an object:

"changes": {
  "attr1" : [
    "sub_attr1": false,
    "sub_attr2": true,
    ...
  ],
  "attr2" : [
    "sub_attr1": false,
    "sub_attr2": true,
    ...
  ],
  ...
}

I want to extract an specific attr of the changes object to a new one. Lets say I want to extract attr1.

"new_obj" : [
  "sub_attr1": false,
  "sub_attr2": true,
  ...
]

and

"changes": {
  "attr2" : [
    "sub_attr1": false,
    "sub_attr2": true,
    ...
  ],
  ...
}

How may I achieve this?

CodePudding user response:

Something like this will work.

const extract = (obj, keyToExtract) => {

    const entries = Object.entries(obj);
    
    const entry = entries.find(([key, value]) => key === keyToExtract);
    if(entry) {
        delete obj[keyToExtract]
        return {
            "new_obj": entry[1]
        }
    }
    
}

extract(obj.changes, "attr1")

CodePudding user response:

Se changes é um objeto então você pode buscar os filhos dele assim changes.filho (objeto)

Sendo array: changes['filho'] (array)

  • Related