如何使用普通的Javascript访问最内层的双嵌套数组/对象?

时间:2016-01-30 21:12:30

标签: javascript arrays object nested

我怀疑答案很简单,但我搜索了这个网站和其他人,但没找到。我有一个双嵌套的数据结构,无法弄清楚如何迭代最内层。我猜它可能涉及forEach()或map()方法,但我尝试过的都没有。

背景: 我已经简化了这个问题的数据。数据(粘贴在下面)存储在包含2个零售商店对象的数组中。每个商店对象都有一个brew install python属性,其值是一个访问对象数组。每次访问(对象)由访问日期标识(假设在日期B最多可以访问商店A)。每个访问对象都包含一个visits属性,其值是访问时进行的一系列事务(购买或退货)。在实际的完整数据中,每个商店每个日期的交易数量变化很大。

我需要帮助的任务: (a)将财产values重命名为key, (b)将属性visitDate重命名为values, (c)删除8个冗余属性(从transactionsstoreID),但保留storeVisitDateaction属性,以及 (d)将财产dollarAmount重命名为dollarAmount

任何帮助都将非常感激。感谢。

dollars

8 个答案:

答案 0 :(得分:3)

你是对的!您可以使用.map()完成大部分操作。新的ES6标准使这很容易,并且使用以下功能,您甚至不会修改任何原始数据!:

array.map(store => {
  //return a new object that takes all the store info, then reassigns the visits key in a new object
  return Object.assign({}, store, {
    //map over visits, and reassign the key key to visitDate
    visits: store.visits.map(({ key: visitDate, values }) => {
      return {
        //return an obj with visit date
        visitDate,
        // do destructuring again to create objects of action,dollars
        transactions: values.map(({ action, dollarAmount: dollars }) => ({ action, dollars }))
      };
    })
  });
});

答案 1 :(得分:1)

working example on jsFiddle here - 只需打开JS控制台即可查看已转换的数据集)

关于以下解决方案的几点意见:

  • 即使你的数据在你粘贴的样本中有更多的键(你提到这是一个简化的集合,所以它可能很重要),它也会工作。
  • 它大量使用“map”,而不是手动迭代数组。我发现它更具可读性。

    // Go over all stores
    stores.map(function(store) {
      // In each store, go over all visits.
      store.visits.map(function(visit) {
        // In each visit, copy 'key' to 'visitDate'
        // and 'values' to 'transactions'.
        // Then delete old names ('key' and 'values').
        visit.visitDate = visit.key;
        visit.transactions = visit.values;
        delete visit.key;
        delete visit.values;
    
        // For each transaction, replace it with a simple
        // map with only 'action' and 'dollars'.
        visit.transactions = visit.transactions.map(function(tx) {
          return {
            action: tx.action,
            dollars: tx.dollarAmount
          };
        });
      });
    });
    

请注意,IE9及更高版本支持map()

答案 2 :(得分:0)

要重命名属性,您可以创建一个具有相同值的新属性,然后创建旧值{。}}。

你可以将它用于所有部分,但是看看你的结构,通过使用delete创建一个新的"优化的"数组,将b,c,d组合在一起看起来更整洁。事务并将其分配给新的transactions属性。



// (I put this in a function so the logic can be at the top of the snippet)
function fixData(stores) {
  // loop stores and their visits
  for (var iStore = 0; iStore < stores.length; iStore++) {
    var store = stores[iStore];

    for (var iVisit = 0; iVisit < store.visits.length; iVisit++) {
      var visit = store.visits[iVisit];

      // (a) rename property key to visitDate
      //   add a new property with the same value then delete the old property
      visit.visitDate = visit.key;
      delete visit.key;

      // (b) rename property values to transactions
      //   add a new property with the same value then delete the old property
      // (c) delete the 8 redundant properties (from storeID to storeVisitDate)
      //   we could delete keys but quicker to map a new object
      // (d) rename property dollarAmount to dollars.
      //   just give the new object property a different name
      visit.transactions = visit.values.map(function(trans) {
        return {
          action: trans.action,
          dollars: trans.dollarAmount
        }
      });
      delete visit.values;
    }
  }

  console.log(stores);
}


var stores = [{
  "storeName": "Ye Olde Candy Shoppe",
  "address": "1313 Vampire Lane, Cityville NY 99999",
  "zipCode": "99999",
  "storeSize": "large",
  "visits": [{
    "key": "5/3/12",
    "values": [{
      "storeID": "53454447",
      "storeName": "Ye Olde Candy Shoppe",
      "city": "Cityville",
      "building": "1313",
      "street": "Vampire Lane",
      "zipcode": "99999",
      "storeSize": "large",
      "storeVisitDate": "5/3/12",
      "action": "Return",
      "dollarAmount": "65.43"
    }, {
      "storeID": "53454447",
      "storeName": "Ye Olde Candy Shoppe",
      "city": "Cityville",
      "building": "1313",
      "street": "Vampire Lane",
      "zipcode": "99999",
      "storeSize": "large",
      "storeVisitDate": "5/3/12",
      "action": "Purchase",
      "dollarAmount": "12.43"
    }, {
      "storeID": "53454447",
      "storeName": "Ye Olde Candy Shoppe",
      "city": "Cityville",
      "building": "1313",
      "street": "Vampire Lane",
      "zipcode": "99999",
      "storeSize": "large",
      "storeVisitDate": "5/3/12",
      "action": "Purchase",
      "dollarAmount": "5.43"
    }]
  }, {
    "key": "12/31/12",
    "values": [{
      "storeID": "53454447",
      "storeName": "Ye Olde Candy Shoppe",
      "city": "Cityville",
      "building": "1313",
      "street": "Vampire Lane",
      "zipcode": "99999",
      "storeSize": "large",
      "storeVisitDate": "12/31/12",
      "action": "Purchase",
      "dollarAmount": "2.53"
    }]
  }, {
    "key": "1/24/13",
    "values": [{
      "storeID": "53454447",
      "storeName": "Ye Olde Candy Shoppe",
      "city": "Cityville",
      "building": "1313",
      "street": "Vampire Lane",
      "zipcode": "99999",
      "storeSize": "large",
      "storeVisitDate": "1/24/13",
      "action": "Return",
      "dollarAmount": "2.53"
    }, {
      "storeID": "53454447",
      "storeName": "Ye Olde Candy Shoppe",
      "city": "Cityville",
      "building": "1313",
      "street": "Vampire Lane",
      "zipcode": "99999",
      "storeSize": "large",
      "storeVisitDate": "1/24/13",
      "action": "Return",
      "dollarAmount": "64.22"
    }]
  }]
}, {
  "storeName": "Mike's Bikes",
  "address": "2626 Aardvark Circle, Townsville NY 88888",
  "zipCode": "88888",
  "storeSize": "small",
  "visits": [{
    "key": "8/8/14",
    "values": [{
      "storeID": "24335234",
      "storeName": "Mike's Bikes",
      "city": "Townsville",
      "building": "2626",
      "street": "Aardvark Circle",
      "zipcode": "88888",
      "storeSize": "small",
      "storeVisitDate": "8/8/14",
      "action": "Purchase",
      "dollarAmount": "443.55"
    }, {
      "storeID": "24335234",
      "storeName": "Mike's Bikes",
      "city": "Townsville",
      "building": "2626",
      "street": "Aardvark Circle",
      "zipcode": "88888",
      "storeSize": "small",
      "storeVisitDate": "8/8/14",
      "action": "Purchase",
      "dollarAmount": "34"
    }, {
      "storeID": "24335234",
      "storeName": "Mike's Bikes",
      "city": "Townsville",
      "building": "2626",
      "street": "Aardvark Circle",
      "zipcode": "88888",
      "storeSize": "small",
      "storeVisitDate": "8/8/14",
      "action": "Purchase",
      "dollarAmount": "12.32"
    }]
  }, {
    "key": "10/3/15",
    "values": [{
      "storeID": "24335234",
      "storeName": "Mike's Bikes",
      "city": "Townsville",
      "building": "2626",
      "street": "Aardvark Circle",
      "zipcode": "88888",
      "storeSize": "small",
      "storeVisitDate": "10/3/15",
      "action": "Purchase",
      "dollarAmount": "233.1"
    }, {
      "storeID": "24335234",
      "storeName": "Mike's Bikes",
      "city": "Townsville",
      "building": "2626",
      "street": "Aardvark Circle",
      "zipcode": "88888",
      "storeSize": "small",
      "storeVisitDate": "10/3/15",
      "action": "Return",
      "dollarAmount": "44.99"
    }]
  }]
}];

fixData(stores);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

如果我们假设你的数组被称为arr,我建议:

arr.forEach(function(currentValue, index, array) {
   currentValue.visits = currentValue.visits.map(function(currentValue, index, array) {
      currentValue.visitDate = currentValue.key;
      delete currentValue.key;
      currentValue.transactions = currentValue.values.map(function(currentValue, index, array) {
         currentValue = {action: currentValue.action, dollars: currentValue.dollarAmount};
         return currentValue;
      });
      delete currentValue.values;
      return currentValue;
   });
});

答案 4 :(得分:0)

好吧,因为这是数据&#39;而不是一些内存中的对象,我猜你是通过使用JSON.parse从JSON获得的。 (如果没有,您仍然可以首先使用JSON.strigify

来使用此方法

您知道JSON.parse是否接受控制此类内容的功能? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

...所以

fixed=JSON.parse(dataString, function(key,value){
 if(key=="key"){this.visitDate=value;return}
 if(key=="values"){this.transactions=value;return}
 if(key=="somethingYouDontWant"){return;}
 //etc...
 return value;    
})

答案 5 :(得分:0)

它的纯javascript没有任何库,并使用简单的地图:

 var y = x.map(function(xs){
      xs.visits = xs.visits.map(function (item){
        return {
          visitDate: item.key,
          transactions: item.values.map(function(v){
            return {
              action: v.action,
              dollars: v.dollarAmount
            };
          })
        };
      });
      return xs;
    });

答案 6 :(得分:0)

使用Array.map()delete运算符的灵活解决方案:

var delete_props = ["storeID","storeName","city","building","street", "zipcode","storeSize", "storeVisitDate"];

 // arr is your initial array
 arr.map(function(obj){
     obj['visits'].map(function(inner_obj){
         inner_obj['visitDate'] = inner_obj['key'];
         delete inner_obj['key'];

         inner_obj['values'].map(function(values_obj){
            values_obj['dollars'] = values_obj['dollarAmount'];
            delete values_obj['dollarAmount'];

            delete_props.forEach(function(v){
                delete values_obj[v];
            });
        });
        inner_obj['transactions '] = inner_obj['values'];
        delete inner_obj['values'];

     });     
 });

答案 7 :(得分:0)

这是另一个解决方案,代码非常简单,但没有优化。

#topbar {  background:rgba(0, 0, 0, 0.65); }