使用包含其他对象的嵌套数组转换/清理对象的最佳方法是什么?

时间:2017-09-01 04:16:48

标签: javascript

我处理从第三方API返回的数据,我真的只需要保留所述对象的某些属性。每个对象都与数组中包含的其他对象大量嵌套,偶尔也只是一个字符串数组的属性。例如,我得到了返回的JSON,例如:

{
  itemId: '12345',
  attributes: [ { attr1: ['red'], attr2: ['large', 'round'], attr3: ['obnoxious'] } ],
  habits: [ 'bounce', 'roll', 'deflate' ]
}

这只是一个例子,但真正的数据非常混乱,我想将所有内容压缩到没有嵌套的单个对象,并以最有效的方式进行。我已经尝试过几个手册'循环这样做的方式,但我觉得必须有一些更有效和资源尽责的方式。我已经查看了ES6包含的使用对象的方法,但我似乎无法正确使用该组合。

我正在使用的真实对象:

{ itemId: [ '263010774375' ],
  title: [ 'Star Wars Destiny Spirit of Rebellion - LEGENDARY' ],
  globalId: [ 'EBAY-US' ],
  primaryCategory: [ { categoryId: [Array], categoryName: [Array] } ],
  galleryURL: [ 
  'http://thumbs4.ebaystatic.com/pict/263010774375404000000004_1.jpg' ],
  viewItemURL: [ 'http://www.ebay.com/itm/Star-Wars-Destiny-Spirit-Rebellion-
  LEGENDARY-/263010774375?var=562018071609' ],
  paymentMethod: [ 'PayPal' ],
  autoPay: [ 'false' ],
  postalCode: [ '78124' ],
  location: [ 'Marion,TX,USA' ],
  country: [ 'US' ],
  shippingInfo: 
   [ { shippingServiceCost: [Array],
       shippingType: [Array],
       shipToLocations: [Array],
       expeditedShipping: [Array],
       oneDayShippingAvailable: [Array],
       handlingTime: [Array] } ],
  sellingStatus: 
   [ { currentPrice: [Array],
       convertedCurrentPrice: [Array],
       sellingState: [Array] } ],
  listingInfo: 
   [ { bestOfferEnabled: [Array],
       buyItNowAvailable: [Array],
       startTime: [Array],
       endTime: [Array],
       listingType: [Array],
       gift: [Array],
       watchCount: [Array] } ],
  returnsAccepted: [ 'true' ],
  condition: [ { conditionId: [Array], conditionDisplayName: [Array] } ],
  isMultiVariationListing: [ 'true' ],
  topRatedListing: [ 'false' ] }`

我想要得到的输出包括将嵌套在嵌套在其他对象属性中的数组嵌套的属性,这些对象属性也嵌套在数组中。我的最终对象只有一个级别,例如:

{
  itemID: '12345',
  title: 'something',
  currentPrice: 20.00,
  endTime: '2017-07-01',
  condition: conditionDisplayName[0], // ex. 'Used'
  location: 'Springfield, USA'
}

1 个答案:

答案 0 :(得分:1)

选中answer

使用递归尝试这样的事情:



var obj = {
    prop: 1,
    arr: [
        { id: 1, name: "larry" },    
        { id: 2, name: "curly" },
        { id: 3, name: "moe" }
    ],
    complex: {
        place: {
            greeting: "hello world"   
        }
    }
};

function flatten(obj){
 var root = {};
 (function tree(obj, index){
   var suffix = toString.call(obj) == "[object Array]" ? "]" : "";
   for(var key in obj){
    if(!obj.hasOwnProperty(key))continue;
    root[index+key+suffix] = obj[key];
    if( toString.call(obj[key]) == "[object Array]" )tree(obj[key],index+key+suffix+"[");
    if( toString.call(obj[key]) == "[object Object]" )tree(obj[key],index+key+suffix+".");   
   }
 })(obj,"");
 return root;
}
   
var flat = flatten(obj);
console.log(flat);