【问题标题】:[Typescript]Taking Object Value and adding it to an Array[Typescript]获取对象值并将其添加到数组中
【发布时间】:2016-05-25 20:03:46
【问题描述】:

您好,我正在尝试从一个对象中获取价值并找到总和。我目前有一个包含三个值和属性的对象,并且想获取这些数字并想添加它们并存储它们

 public selectedItem = {name:" "}; // Separate Object that displays values. Dont want to display it just add the value

public shoppingListItems = [
      {name: "Milk" ,number: 100},
      {name: "Sugar", number: 22,},
      {name: "bread", number: 12}
    ]; 

 public Price = [];

this.Price.push(shoppingListItem.keys(this.selectedItem)); // Attempt to push my shopping list items onto the Price Array
     console.log(this.Price); // Check is the values are actually stored.

我试图创建一个单独的数组并通过执行以下操作将值存储在那里,以便我可以将我的数值推送到我的数组中,但它似乎没有这样做。有没有办法从我的对象中取出值并将它们添加到我的数组中,以便我可以存储它们并可能在以后添加它们?

【问题讨论】:

    标签: javascript arrays object typescript


    【解决方案1】:

    使用map 查找以创建一个新数组,其中包含原始数组中对象的属性值,并使用reduce 获取这些数字的总和。

    这里有一个简单的例子,你可以应用到你的场景中:

    const shoppingListItems = [
        {name: "Milk", number: 100},
        {name: "Sugar", number: 22},
        {name: "bread", number: 12}
    ]; 
    
    // creates an array of the `number` property: [100, 22, 12]
    const numbers = shoppingListItems.map(i => i.number);
    // gets the sum of the array of numbers: 134
    const sum = numbers.reduce((a, b) => a + b, 0);
    

    【讨论】:

    • “地图”甚至没有必要
    • @AlexanderDerck 是的,你可以这样做:shoppingListItems.reduce((a, b) => a.number + b.number, 0)
    猜你喜欢
    • 2018-10-14
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    相关资源
    最近更新 更多