簡體   English   中英

使用typescript循環遍歷json中的可能數組

[英]Loop through possible arrays in json with typescript

不是問如何在打字稿中循環遍歷數組。 我的問題有點不同,所以讓我先解釋一下。

我有一個看起來像這樣的json:

{
    "forename": "Maria",
    "colors": [
      {
        "name": "blue",
        "price": 10
      },
      {
        "name": "yellow",
        "price": 12
      }
    ],
    "items": [
      {
        "name": "sword",
        "price": 20
      }
    ],
    "specialPowers": [
      {
        "name": "telekinesis",
        "price": 34
      }
    ]
  },
  {
    "forename": "Peter",
    "colors": [
      {
        "name": "blue",
        "price": 10
      }
    ],
    "items": [
      {
        "name": "hat",
        "price": 22
      },
      {
        "name": "hammer",
        "price": 27
      }
    ]
  }

  // some more persons

如您所見,我的人員可以具有顏色,項目或specialPowers之類的數組。 但是一個人也可以不擁有任何一個。 如您所見,Maria具有數組specialPowers,而Peter沒有。

我需要一個函數來檢查一個人是否具有這些數組之一,如果有,我必須將其價格總計。 所以我想要一個人擁有的所有東西的總價。

目前,我具有三個基本如下的功能:

getTotalOfColors(person) {
    let total = 0;
    if(person.colors)
      for (let color of person.colors) {
        total = total + color.price;
      }
    return total;
  }

getTotalOfItems(person) {
    let total = 0;
    if(person.items)
      for (let item of person.items) {
        total = total + item.price;
      }
    return total;
  }

 // SAME FUNCTION FOR SPECIALPOWERS

我基本上有三次相同的功能。 唯一的區別是,我正在遍歷另一個數組。 但是這些功能都一樣。 他們首先檢查人員是否擁有該數組,其次他們遍歷該數組以將價格加到總計中。

最后,我的問題是:有一種方法可以在ONE函數中完成所有這些操作嗎? 因為它們基本上都在做相同的事情,所以我不需要冗余的代碼。 我的想法是遍歷所有數組,同時檢查人員是否擁有該數組,如果有,將其價格加到總計中。

我認為函數看起來像這樣:

getTotal(person) {
        let total = 0;
        for (let possibleArray of possibleArrays){
          if(person.possibleArray )
            for (let var of person.possibleArray ) {
              total = total + var.price;
            }
          }
        return total;
      }

這樣,我將擁有一個“通用”函數,但為此,我必須擁有一個可能的數組,例如: maysArrays = [colors,items,specialPowers]我該如何實現? 我應該如何在代碼中以及在哪里編寫此數組? 還是針對這個問題有更好的解決方案?

我創建了一個似乎可以解決問題的函數:

function totalPrice(data) {
  let total = 0;
  for (person of data) {                  //Go through the array of people
    for (prop in person) {                //Go through every property of the person
      if (Array.isArray(person[prop])) {  //If this property is an array
        for (element of person[prop]) {   //Go through this array
                                          //Check if `price` is a Number and
                                          //add it to the total
          if (!isNaN(element.price)) total += element.price;
        }
      }
    }
  }

  return total;
}

演示:

 function totalPrice(data) { let total = 0; for (person of data) { for (prop in person) { if (Array.isArray(person[prop])) { for (element of person[prop]) { if (!isNaN(element.price)) total += element.price; } } } } return total; } let data = [ { "forename": "Maria", "colors": [{ "name": "blue", "price": 10 }, { "name": "yellow", "price": 12 } ], "items": [{ "name": "sword", "price": 20 }], "specialPowers": [{ "name": "telekinesis", "price": 34 }] }, { "forename": "Peter", "colors": [{ "name": "blue", "price": 10 }], "items": [{ "name": "hat", "price": 22 }, { "name": "hammer", "price": 27 } ] } ]; console.log(totalPrice(data)); 

您可以使用reduce函數以及includes的函數來選擇所需的目標。

 var inputData = [{ "forename": "Maria", "colors": [{ "name": "blue", "price": 10 }, { "name": "yellow", "price": 12 } ], "items": [{ "name": "sword", "price": 20 }], "specialPowers": [{ "name": "telekinesis", "price": 34 }] }, { "forename": "Peter", "colors": [{ "name": "blue", "price": 10 }], "items": [{ "name": "hat", "price": 22 }, { "name": "hammer", "price": 27 } ] }]; function totalize(possibleArrays, data) { return data.reduce((a, c) => { return a + Object.keys(c).reduce((ia, k) => { if (possibleArrays.includes(k)) c[k].forEach(p => ia += p.price); return ia; }, 0); }, 0); } var total = totalize(["colors", "items", "specialPowers"], inputData); console.log(total); 

這樣的事情也應該做到這一點,我只是將結果記錄在控制台中,但是您可以使用它們完成幾乎所有的操作:

const getSum = (person, prop) => {
    let total = 0;
    if(person[prop])
      for (let value of person[prop]) {
        total = total + value.price;
      }
    return total;
}

const props = ['colors', 'items', 'specialPowers']

console.log(data.map(person => props.map(prop => getSum(person, prop))));

編輯

我沒有得到您想要一次匯總一個人的所有財產的信息,這絕對是我想要的代碼:

const sum = (a, b) => a + b;

const props = ['colors', 'items', 'specialPowers'] 

data.map(person => 
    props.map(prop =>
        (person[prop] || [])
            .map(({price}) => price)
            .reduce(sum, 0)
    ).reduce(sum, 0)
)

如果要對所有人的總價求和:

data.map(person => 
    props.map(prop =>
        (person[prop] || [])
            .map(({price}) => price)
            .reduce(sum, 0)
    ).reduce(sum, 0)
).reduce(sum, 0)

暫無
暫無

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

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