【问题标题】:How can I remove values and add an index column to a JavaScript object?如何删除值并将索引列添加到 JavaScript 对象?
【发布时间】:2018-10-16 09:56:41
【问题描述】:

我收到了这些数据:

[]
0:{time: 1525355921817, sym: "AAPL", price: 169.16, size: 98, stop: false, …}
1:{time: 1525355923216, sym: "AAPL", price: 170.15, size: 6, stop: false, …}
2:{time: 1525355923216, sym: "AAPL", price: 170.06, size: 57, stop: false, …}

我需要把它变成以下格式:

0:{"time": 1525355921817, "sym": "AAPL", "price": 169.16, "index": 0} 
1:{"time": 1525355923216, "sym": "AAPL", "price": 170.15, "index": 1} 
2:{"time": 1525355923216, "sym": "AAPL", "price": 170.06, "index": 2}

基本上只是删除大小并停止并添加索引列。我还需要能够以this.data.price 的身份访问它并取回所有价格值......这甚至可能吗?此数据来自 Angular 中的服务

我怎样才能做到这一点? (请注意,我不是 Angular 或 javascript 的经验丰富的用户)

【问题讨论】:

  • 通常您不需要在对象中使用索引列。当您真正需要它或访问ngFor 的索引时,使用Array#indexOf() 总是很容易。在 Angular 应用程序中如何实际使用它?

标签: javascript arrays json angular typescript


【解决方案1】:

您可以使用.map() 创建所需的输出:

let data = [{time: 1525355921817, sym: "AAPL", price: 169.16, size: 98, stop: false},{time: 1525355923216, sym: "AAPL", price: 170.15, size: 6, stop: false},{time: 1525355923216, sym: "AAPL", price: 170.06, size: 57, stop: false}];

let result = data.map((o, i) => ({
  time: o.time,
  sym: o.sym,
  price: o.price,
  index: i
}));

console.log(result);

【讨论】:

    【解决方案2】:

    您可以map 对象数组。您可以解构每个对象以获得更短的代码。

    let arr = [{time: 1525355921817, sym: "AAPL", price: 169.16, size: 98, stop: false,},{time: 1525355923216, sym: "AAPL", price: 170.15, size: 6, stop: false,},{time: 1525355923216, sym: "AAPL", price: 170.06, size: 57, stop: false,}];
    
    let result = arr.map(({size,stop,...r}, i) => Object.assign(r, {index: i}));
    
    console.log( result );

    文档:map()Destructuring Assignment

    【讨论】:

      【解决方案3】:

      我还需要能够以 this.data.price 的形式访问它并取回所有价格值......这甚至可能吗?

      假设数组在data下:

       const groupValue = (arr, key) => arr[key] = arr.map(el => el[key]);
      
       groupValue(this.data, "price");
      
       console.log(this.data.price);
      

      【讨论】:

        猜你喜欢
        • 2013-06-30
        • 2017-02-21
        • 2010-11-13
        • 1970-01-01
        • 1970-01-01
        • 2017-06-22
        • 1970-01-01
        相关资源
        最近更新 更多