如何在我的JavaScript字典中访问此属性?

huangapple go评论50阅读模式
英文:

How can I access this property in my dictionary in js?

问题

我以为我知道如何遍历字典,但是我的循环是错误的。我尝试访问每个子项的名称,但我的代码不起作用。
这是我做的事情:

list = [
      {
        title: '杂货',
        items: [
          {
            id: 4,
            title: '食物',
            cost: 540,
          },
          {
            id: 5,
            title: '卫生',
            cost: 235,
          },
          {
            id: 6,
            title: '其他',
            cost: 20,
          },
        ],
      }];

function calculateCost(){
let total = 0;
Object.keys(list).forEach((k) => { for (i in k.items) { total += i.data; } });
console.log(total);
return total;
}
英文:

I thought I understood how to loop through a dictionary, but my loop is wrong. I try to access the name of each sub item but my code does not work.
Here is what I did:

list = [
      {
        title: 'Groceries',
        items: [
          {
            id: 4,
            title: 'Food',
            cost: 540 ,
          },
          {
            id: 5,
            title: 'Hygiene',
            cost: 235,
          },
          {
            id: 6,
            title: 'Other',
            cost: 20,
          },
        ],
      }];

function calculateCost(){
let total = 0;
Object.keys(list).forEach((k) => { for (i in k.items) { total += i.data; } });
console.log(total);
return total;
}

答案1

得分: 1

你的列表是一个数组,包括1个对象,而这个对象两个属性,分别是标题项目。这里的项目是一个对象数组,每个对象都有一个成本属性。要计算总成本,你需要循环遍历项目数组,以下是如何操作的示例代码:

let list = [
  {
    title: 'Groceries',
    items: [
      {
        id: 4,
        title: 'Food',
        cost: 540,
      },
      {
        id: 5,
        title: 'Hygiene',
        cost: 235,
      },
      {
        id: 6,
        title: 'Other',
        cost: 20,
      },
    ],
  }
];

function calculateCost() {
  let total = 0;
  list[0].items.forEach(el => {
    total += el.cost;
  });
  console.log(total);
  return total;
}

calculateCost();

这段代码将计算总成本并在控制台输出。

英文:

Your list is an array includes 1 object and this object has two properties title and items the items here is an array of objects each one of these objects has property cost so to calculate the total cost you need to loop through items array, here is how you do it:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let list = [
      {
        title: &#39;Groceries&#39;,
        items: [
          {
            id: 4,
            title: &#39;Food&#39;,
            cost: 540 ,
          },
          {
            id: 5,
            title: &#39;Hygiene&#39;,
            cost: 235,
          },
          {
            id: 6,
            title: &#39;Other&#39;,
            cost: 20,
          },
        ],
      }];

function calculateCost(){
let total = 0;
  list[0].items.forEach(el =&gt; {
    total += el.cost;
  })
  console.log(total)
  return total;
}

calculateCost();

<!-- end snippet -->

答案2

得分: 1

您的list是一个数组,而不是对象。
可以使用Array.prototype.reduce来替代Object.keys()

const calculateCost = (arr) => arr.reduce((tot, ob) =>
  ob.items.reduce((sum, item) => sum + item.cost, tot), 0);

const list = [
  {
    title: 'Groceries',
    items: [
      {id: 4, title: 'Food', cost: 10},
      {id: 5, title: 'Hygiene', cost: 20},
      {id: 6, title: 'Other', cost: 30}
    ]
  }, {
    title: 'Other',
    items: [
      {id: 8, title: 'Scuba gear', cost: 39}
    ],
  }
];

console.log(calculateCost(list));  // 99
英文:

Your list is an Array, not an Object.
Instead of Object.keys() use Array.prototype.reduce:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const calculateCost = (arr) =&gt; arr.reduce((tot, ob) =&gt;
  ob.items.reduce((sum, item) =&gt; sum + item.cost, tot), 0);

const list = [
  {
    title: &#39;Groceries&#39;,
    items: [
      {id: 4, title: &#39;Food&#39;, cost: 10},
      {id: 5, title: &#39;Hygiene&#39;, cost: 20},
      {id: 6, title: &#39;Other&#39;, cost: 30}
    ]
  }, {
    title: &#39;Other&#39;,
    items: [
      {id: 8, title: &#39;Scuba gear&#39;, cost: 39}
    ],
  }
];

console.log(calculateCost(list));  // 99

<!-- end snippet -->

答案3

得分: 1

以下是翻译好的部分:

// 拓展 @Roko 和 @mmh4all 的回答,以下代码添加了多个验证语句,以处理数据中深度嵌套属性不符合预期的情况。

const calculateCost = (orders) => {
    let listOfCosts = [];
    // 对于 'orders' 数组中的每个 'order' 对象,
    // 将每个订单中的 'cost' 属性的值添加到 'listOfCosts' 数组中。
    orders.forEach(order => {
        // 如果 'order.items' 不是数组,返回。
        if (!Array.isArray(order.items)) { return; }
        // 使用 isNaN 和 parseFloat 处理 'cost' 属性的值。
        const orderCostArr = order.items.map(item =>
            isNaN(item.cost) ? 0 : parseFloat(item.cost, 10));
        if (orderCostArr.length === 0) { return; }
        // 将 'orderCostArr' 连接到 'listOfCosts' 数组中。
        listOfCosts.push(...orderCostArr);
    });
    // 使用 'reduce' 方法计算 'listOfCosts' 数组中的总成本。
    const totalCost = listOfCosts.reduce(
        (accumulator, currentValue) => accumulator + currentValue, 0);
    return totalCost;
};

const list = [
    {
        title: 'Groceries',
        items: [
            { id: 4, title: 'Food', cost: 10 },
            { id: 3, title: 'Baked goods', cost: 20 },
            { id: 5, title: 'Hygiene', cost: 0 },
            { id: 6, title: 'Other' }
        },
    },
    {
        title: 'Gear',
        items: {},
    },
    {
        title: 'Accessories',
        items: [],
    },
    {
        title: 'Bags',
    },
    {
        title: 'Other',
        items: [
            { id: 10, title: 'Scuba gear', cost: "5" },
            { id: 8, title: 'Scuba gear', cost: "err" },
            { id: 9, title: 'Scuba gear', cost: 59 },
        ],
    },
];

console.log(calculateCost(list));  // 94

希望这对您有所帮助。

英文:

Expanding on @Roko's and @mmh4all's answers, the following code adds several verification statements to handle cases where a deeply nested property in your data is not what you expect it to be.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const calculateCost = (orders) =&gt; {
let listOfCosts = [];
// For each &#39;order&#39; object in the &#39;orders&#39; array, 
// add the value of the &#39;cost&#39; property of each item 
// in the order to &#39;listOfCosts&#39; array.
orders.forEach(order =&gt; {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray(order.items)) { return; }
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat
const orderCostArr = order.items.map(item =&gt;
isNaN(item.cost) ? 0 : parseFloat(item.cost, 10));
if (orderCostArr.length === 0) { return; }
// Concatenate &#39;orderCostArr&#39; to the &#39;listOfCosts&#39; array
//listOfCosts = listOfCosts.concat(orderCostArry);
// Alternate approach is to use the spread syntax (...) to
// push the items in the array returned by &#39;order.items.map()&#39;
// into the &#39;listOfCosts&#39; array.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
listOfCosts.push(...orderCostArr);
});
// Use the &#39;reduce&#39; method on the &#39;listOfCosts&#39; array
// to get the total cost.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
const totalCost = listOfCosts.reduce(
(accumulator, currentValue) =&gt; accumulator + currentValue, 0);
return totalCost;
};
const list = [
{
title: &#39;Groceries&#39;,
items: [
{ id: 4, title: &#39;Food&#39;, cost: 10 },
{ id: 3, title: &#39;Baked goods&#39;, cost: 20 },
{ id: 5, title: &#39;Hygiene&#39;, cost: 0 },
{ id: 6, title: &#39;Other&#39; }
]
}, {
title: &#39;Gear&#39;,
items: {},
}, {
title: &#39;Accessories&#39;,
items: [],
}, {
title: &#39;Bags&#39;,
}, {
title: &#39;Other&#39;,
items: [
{ id: 10, title: &#39;Scuba gear&#39;, cost: &quot;5&quot; },
{ id: 8, title: &#39;Scuba gear&#39;, cost: &quot;err&quot; },
{ id: 9, title: &#39;Scuba gear&#39;, cost: 59 }
],
}
];
console.log(calculateCost(list));  // 94

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月16日 18:30:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定