2017-02-24 52 views
0

假設我有以下的JSON文件,我想與lodash preferrably返回「existing.primaryBundle.products」數組:如何使用lodash從json中返回一個childobject?

{ 
    "existing": { 
    "hasPlatinum": false, 
    "primaryBundle": { 
     "id": "2008", 
     "name": "TV - Entertainment, Sport", 
     "products": [ 
     { 
      "name": "Entertainment", 
      "id": "100", 
      "price": 2600, 
      "gifted": false 
     }, 
     { 
      "name": "Sport", 
      "id": "107", 
      "price": 2500, 
      "gifted": false, 
      "swappableProducts": [ 
      { 
       "name": "Movies", 
       "id": "105", 
       "price": 2000, 
       "gifted": false 
      } 
      ] 
     } 
     ] 
    }, 
    "extrasBundle": { 
     "id": "131", 
     "name": "Optional Extras - MUTV (Sports), LFCTV (Sports), Chelsea TV (Sports)", 
     "products": [ 
     { 
      "name": "MUTV (Sports)", 
      "id": "665", 
      "price": 0, 
      "gifted": false 
     }, 
     { 
      "name": "LFCTV (Sports)", 
      "id": "666", 
      "price": 0, 
      "gifted": false 
     }, 
     { 
      "name": "Chelsea TV (Sports)", 
      "id": "667", 
      "price": 0, 
      "gifted": false 
     } 
     ] 
    } 

    } 
} 

我曾嘗試lodash並使用此聲明:

列表2 = _.pick(現有,'primaryBundle.products')

但是,這會返回一個錯誤,而不是想要的結果。我怎樣才能選擇這個產品陣列?

+4

假設您已經解析的JSON字符串* *獲取對象'obj',你可以說'列表2 = obj.existing.primaryBundle.products'。不需要Lodash。 – nnnnnn

回答

0

你可以使用_.get(nameOfObject, 'existing.primaryBundle.products')當然你需要命名你的對象,就像我在下面用sampleObject所做的那樣;

退房的lodash docs

const sampleObject = { 
    "existing": { 
    "hasPlatinum": false, 
    "primaryBundle": { 
     "id": "2008", 
     "name": "TV - Entertainment, Sport", 
     "products": [{ 
     "name": "Entertainment", 
     "id": "100", 
     "price": 2600, 
     "gifted": false 
     }, { 
     "name": "Sport", 
     "id": "107", 
     "price": 2500, 
     "gifted": false, 
     "swappableProducts": [{ 
      "name": "Movies", 
      "id": "105", 
      "price": 2000, 
      "gifted": false 
     }] 
     }] 
    }, 
    "extrasBundle": { 
     "id": "131", 
     "name": "Optional Extras - MUTV (Sports), LFCTV (Sports), Chelsea TV (Sports)", 
     "products": [{ 
     "name": "MUTV (Sports)", 
     "id": "665", 
     "price": 0, 
     "gifted": false 
     }, { 
     "name": "LFCTV (Sports)", 
     "id": "666", 
     "price": 0, 
     "gifted": false 
     }, { 
     "name": "Chelsea TV (Sports)", 
     "id": "667", 
     "price": 0, 
     "gifted": false 
     }] 
    } 
    } 
} 

console.log(_.get(sampleObject, 'existing.primaryBundle.products')); 
0

爲什麼它返回一個錯誤的主要原因是因爲existing不是全局範圍的對象,你必須分配對象像const obj = {...}一些變量,然後將參數傳遞給_pick方法obj.existing,但我沒有看到在這裏使用lodash的原因,你可以直接引用該對象的路徑。