Home > database >  How to get the value referring to a specific key in the object and its children?
How to get the value referring to a specific key in the object and its children?

Time:08-20

In the output of a form, I have an object that includes the field name and a key "value" referring to the value. The field can also be an object with another key "value". I would like to get only the values ​​contained in "value". Here's the example:

original object:

{
  inputA: 1354,
  inputB: "String Value",
  inputC: [
    {
      value: 1,
      label: "Value 1"
    },
    {
      value: 2,
      label: "Value 2"
    },
    {
      value: 4,
      label: "Value 3"
    }
  ],
  inputD: {
    value: 16,
    label: "Value 16"
  },
  inputE: {
    value: 1,
    label: "Value 1"
  },
  inputF: {
    subInputA: {
      value: "String Value",
      label: "Value of Value"
    },
    subInputB: {
      value: 1,
      label: "Value 1"
    }
  }
}

Result I would like to get:

{
  inputA: 1354,
  inputB: "String Value",
  inputC: [1,2,3],
  inputD: 16,
  inputE: 1,
  inputF: {
    subInputFA: "String Value",
    subInputFB: 1
  }
}

CodePudding user response:

Alright, I hope I understood your question. If not please elaborate your problem.


**EDIT**
Why did somebody down voted this answer? It works and this is the sollution. I worked hard to get it done. Now I am disappointed :/


There's a code that will do what you asked. At least what the expected output should look like.

//this is your original object
let originalObject = {
  inputA: 1354,
  inputB: "String Value",
  inputC: [
    { value: 1,  label: "Value 1"  },
    { value: 2,  label: "Value 2"  },
    { value: 4,  label: "Value 3"  }
  ],
  inputD: { value: 16,  label: "Value 16" },
  inputE: { value: 1,   label: "Value 1"  },
  inputF: {
    subInputA: { value: "String Value", label: "Value of Value"  },
    subInputB: { value: 1,    label: "Value 1"  }
  }
}

//expected output
/*
{
  inputA: 1354,
  inputB: "String Value",
  inputC: [1,2,3],
  inputD: 16,
  inputE: 1,
  inputF: {
    subInputFA: "String Value",
    subInputFB: 1
  }
}
*/

//my code
let ans = {}

function digDeep (obj){
    if(typeof obj ==='number' || typeof obj === 'string') return obj
    else if( typeof obj === 'object' && obj.length===undefined){
        let keys = Object.keys(obj)
        if(keys.indexOf('value')!=-1) return obj.value
        let pom = {}
        keys.forEach(key=> pom[key]=digDeep(obj[key]) )
        return pom
    }else if( typeof obj ==='object' && obj.length>0) return obj.map(el=>digDeep(el) )
}

ans = digDeep(originalObject)

//print the output
console.log(ans)
 

Output:

{ inputA: 1354,
  inputB: 'String Value',
  inputC: [ 1, 2, 4 ],
  inputD: 16,
  inputE: 1,
  inputF: { subInputA: 'String Value', subInputB: 1 } }
  • Related