简体   繁体   English

从2个HTTP请求的元素创建新数组

[英]Create new array from elements of 2 http requests

I have 2 json arrays which are the results of 2 http.get requests. 我有2个json数组,它们是2个http.get请求的结果。 One contains a watch list like: 其中包含一个监视列表,例如:

json1= [
{“id”:6,”ticker”:”PG”,”gt_lt”:”<“,”price_trigger”:75},
{“id”:8,”ticker”:”T”,”gt_lt”:”<“,”price_trigger”:39.5},
{“id”:9,”ticker”:”WM”,”gt_lt”:”<“,”price_trigger”:60}
];

The second one contains stock pricing info: 第二个包含股票定价信息:

json2 = [
{“symbol”:”PG”,”name”:”Procter & Gamble Company (The) “,”lastTradeDate”:null,”lastTradePriceOnly”:88.4,”change”:0.35,”dividendYield”:3.04,”peRatio”:23.93,”volume”:1333524},
{“symbol”:”T”,”name”:”AT&T Inc.”,”lastTradeDate”:null,”lastTradePriceOnly”:39.94,”change”:-0.26,”dividendYield”:4.78,”peRatio”:17.22,”volume”:2865061},
{“symbol”:”WM”,”name”:”Waste Management, Inc. Common S”,”lastTradeDate”:null,”lastTradePriceOnly”:62.98,”change”:0.17,”dividendYield”:2.61,”peRatio”:24.61,”volume”:276554}
];

I wish to create a third json array or object comprised of the first array and all elements of second array where "ticker"(json1) == "symbol"(json2). 我希望创建由第一个数组和第二个数组的所有元素组成的第三个json数组或对象,其中“ ticker”(json1)==“ symbol”(json2)。 This would allow me to utilize ngFor on the new array and get all the required info into one list or table. 这将使我能够在新数组上使用ngFor并将所有必需的信息收集到一个列表或表中。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Here is a way to do what you want: 这是一种执行所需操作的方法:

let json3 = json1.map(item1 => [item1, json2.find(item2 => item2.symbol === item1.ticker)])

The result is an array consisting of subarrays of two elements: item json1 and associated item of json2 . 结果是一个由两个元素的子数组组成的数组:item json1和关联的item json2


EDIT A find polyfill: 编辑查找polyfill:

Here is a polyfill for the find method that I grabbed from MDN : 这是我从MDN抓取find方法的polyfill

if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    value: function(predicate) {
     'use strict';
     if (this == null) {
       throw new TypeError('Array.prototype.find called on null or undefined');
     }
     if (typeof predicate !== 'function') {
       throw new TypeError('predicate must be a function');
     }
     var list = Object(this);
     var length = list.length >>> 0;
     var thisArg = arguments[1];
     var value;

     for (var i = 0; i < length; i++) {
       value = list[i];
       if (predicate.call(thisArg, value, i, list)) {
         return value;
       }
     }
     return undefined;
    }
  });
}

Place this somewhere at the start of your program. 将此放置在程序的开始位置。 It can go in a script file loaded by the browser early on. 它可以很早地进入浏览器加载的脚本文件。

You can do it like this, easy way: 您可以这样简单地操作:

var json3 = [];

json1.forEach(function(v,i){
    json2.forEach(function(b,j){
        if(b.symbol == v.ticker)
            json3.push(Object.assign({},v,b));
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM