gpt4 book ai didi

javascript - 使用 typescript 循环遍历 json 中可能的数组

转载 作者:行者123 更新时间:2023-11-28 17:35:09 26 4
gpt4 key购买 nike

不是问如何在 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

如您所见,我的人员可以拥有颜色、元素或特殊权力等数组。但一个人也可以没有这些。正如您所看到的,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

同一个功能我基本上用了3次了。唯一的区别是,我正在循环另一个数组。但这些功能的作用都是一样的。他们首先检查该人是否拥有该数组,然后循环遍历该数组以将价格添加到总计中。

最后我的问题是:有没有一种方法可以在一个函数中完成这一切?因为他们基本上都在做同样的事情,我不想有多余的代码。我的想法是循环遍历所有数组,同时检查该人是否拥有该数组,如果有,则将其价格添加到总数中。

我假设该函数看起来像这样:

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;
}

像这样,我将有一个“通用”函数,但为此我必须有一个可能的数组数组,如下所示:possibleArrays = [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));

关于javascript - 使用 typescript 循环遍历 json 中可能的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49300547/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com