簡體   English   中英

如何獲取引用 object 及其子項中特定鍵的值?

[英]How to get the value referring to a specific key in the object and its children?

在表格的 output 中,我有一個 object ,其中包括字段名稱和引用該值的鍵“值”。 該字段也可以是帶有另一個鍵“值”的 object。 我只想獲取“值”中包含的值。 這是示例:

原裝 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"
    }
  }
}

結果我想得到:

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

有一個代碼可以滿足您的要求。 至少預期的 output 應該是什么樣子。

 //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 } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM