【问题标题】:How to add two arrays data in Ionic 2如何在 Ionic 2 中添加两个数组数据
【发布时间】:2017-07-18 16:41:10
【问题描述】:

我是 Ionic 2 的初学者。我想根据他们的位置添加到数组元素中。 例如:我有 2 个数组。

  1. 标签:[Lillium,Gerbera,Gerbera,Lillium,Rose,Rose]

  2. 数据:[10, 20, 10, 30, 20,10]

现在我想从标签[]中删除冗余并希望从数据[]中添加它们的值

我的最终数组应该是

标签:[百合、非洲菊、玫瑰]

数据:[40,30,30]

我已经从这种类型的 Json 中提取数据:

 var qp = []
        for (var i of res.data) {
             qp.push(i.quantity_produced);
        console.log(res.data);
         console.log(qp);

        var name = []
          for (var i of res.data) {
             name.push(i.product);
              var s= [new Set(name)];
        console.log(res.data);
        console.log(name);

【问题讨论】:

  • 数据和标签是什么关系?
  • 每个标签都有价值吗?因为这种结构非常混乱,所以最好使用对象数组。此外,如果一开始就没有冗余,您可以使用 javascript Sets 确保唯一性。
  • 它们在单个 json 中,提供花的名称和生产

标签: angularjs arrays ionic2 angularjs-ng-repeat hybrid-mobile-app


【解决方案1】:

试试这个:

let labels = ['Lillium', 'Gerbera', 'Gerbera', 'Lillium', 'Rose', 'Rose'];
let Data = [10, 20, 10, 30, 20, 10];

//for each unique label....
let result = [...new Set(labels)]

//... get each occurence index ...
.map(value => labels.reduce((curr, next, index) => {
  if (next == value)
    curr.push(index);
  return curr;
}, []))

//... and reducing each array of indexes using the Data array gives you the sums
.map(labelIndexes => labelIndexes.reduce((curr, next) => {
  return curr + Data[next];
}, 0));

console.log(result);

根据您的评论,事情似乎可以轻松很多

let data = [{product: 'Lillium',quantity_produced: 10}, {product: 'Gerbera',quantity_produced: 20},{product: 'Gerbera',quantity_produced: 10}, {product: 'Lillium',quantity_produced: 30}, {product: 'Rose',quantity_produced: 20}, {product: 'Rose',quantity_produced: 10}];

let result = data.reduce((curr, next) => {
  curr[next.product] = (curr[next.product] || 0) + next.quantity_produced;
  return curr;
}, {});

console.log(result);

【讨论】:

  • 我有这种类型的精确标签和数据: var qp = [] for (var i of res.data) { qp.push(i.quantity_produced);控制台.log(res.data);控制台.log(res.data); var name = [] for (var i of res.data) { name.push(i.product); var s= [新集合(名称)];控制台.log(res.data); @Vanojx1
  • 但是先生我们的数据是来自json的动态数据。正如您所建议的,这非常适用于静态数组。这是我的 json 链接:factoryunlock.in/sundar/public/api/v1/production@Vanojx1 先生
  • 您的数据可以是动态的,只需将我的示例中的数据替换为您的 json 中的数据...。CHECK THIS
  • 先生,我可以通过 json 链接而不是静态 json 响应,请建议@Vanojx1 先生
  • 如何通过 http 获取 json 数据,它与这个问题无关...查看 angular2 文档
猜你喜欢
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 2018-06-29
相关资源
最近更新 更多