2016-04-01 9 views
0

JavaScriptオブジェクトがあります。オブジェクトの一部を抽出し、新しいオブジェクト配列を作成する必要があります。主な注意点は、新しいオブジェクトではキー名が異なっていることです(Googleタグマネージャとキー名はあらかじめ定義されています)。オブジェクトから部分を抽出し、新しい縮小版を作成する

このプロジェクトではすでにunderscore.jsを使用していますが、バニラJSソリューションがよりシンプルな場合は必須ではありません。

これは私が(data.buildingsから)部品を抽出し、この新たなオブジェクト配列

[{ 
    'name': 'Some title', 
    'id': '120', 
    'location': '4444' 
}, 
{ 
    'name': 'Some other title', 
    'id': '121', 
    'location': '5555' 
}, 
{ 
    'name': 'Some different title', 
    'id': '122', 
    'location': '6666' 
}] 

どれを作成したい既存のオブジェクト

{ 
    'object_handle': 'handle', 
    'something_else': 'ladela', 
    'some_other_thing': 'other thing', 
    'data':{ 
     'object_id': 120, 
     'buildings':[ 
     { 
      'item_id':120, 
      'title':'Some title', 
      'not_needed': 'Don't need this', 
      'locations':[ 
       { 
        'location_id':4444 
       } 
      ] 
     }, 
     { 
      'item_id':121, 
      'title':'Some other title', 
      'not_needed': 'Don't need this', 
      'locations':[ 
       { 
        'location_id':5555 
       } 
      ] 
     }, 
     { 
      'item_id':122, 
      'title':'Some different title', 
      'not_needed': 'Don't need this', 
      'locations':[ 
       { 
        'location_id':6666 
       } 
      ] 
     } 
     ] 
    } 
} 

の簡易版であります提案は高く評価されます。私はあなたのオブジェクトとしてのvar Aみなさhttps://jsfiddle.net/e7t8ypmd/2/

+0

'map.'を' data.buildings'で実行します。 –

+0

これはうまくいった - https://jsfiddle.net/e7t8ypmd/3/ – MikeeBee

答えて

0

はこれを試してみてください...

...

var a ={your object}; 
 

 
var b = _.each(a.data.buildings, function (item) { 
 
        item.name = item.title; 
 
        item.id = item.item_id; 
 
        item.location = item.locations[0].location_id; 
 
       }); 
 

 
var plucked = b.map(function (model) { 
 
        return _.pick(model, ["name", "id","location"]); 
 
       });
- それが助け場合

は、私がデータをいじるを作成しました

変数 'plucked'には必要なプロパティのみが含まれます。

+0

これは、魅力を働かせました、ありがとう! – MikeeBee

関連する問題