Javascript 通过连接两个阵列来创建新阵列
我有两个不同的数组,一个填充独特的货币,另一个填充独特的国家 两个数组都有一个匹配的列,在currency数组中称为Javascript 通过连接两个阵列来创建新阵列,javascript,arrays,typescript,Javascript,Arrays,Typescript,我有两个不同的数组,一个填充独特的货币,另一个填充独特的国家 两个数组都有一个匹配的列,在currency数组中称为counter\u currency,在country数组中称为reporter 我之所以要创建这个新数组,是因为原来的货币数组对我来说已经不够了。我现在想要一个两位数的ISO代码,它可以在国家数组中找到,并包含在我的货币数据中 货币数组是具有以下格式的对象数组: export interface CurrencyInterface { currency_code: str
counter\u currency
,在country数组中称为reporter
我之所以要创建这个新数组,是因为原来的货币数组对我来说已经不够了。我现在想要一个两位数的ISO代码,它可以在国家数组中找到,并包含在我的货币数据中
货币数组是具有以下格式的对象数组:
export interface CurrencyInterface {
currency_code: string;
base_currency_code: string;
base_currency: string;
counter_currency_code: string;
counter_currency: string;
}
export interface ReporterInterface {
reporter_code: number;
reporter: string;
reporter_iso: string;
reporter_iso_2?: string;
}
货币数组是具有以下格式的对象数组:
export interface CurrencyInterface {
currency_code: string;
base_currency_code: string;
base_currency: string;
counter_currency_code: string;
counter_currency: string;
}
export interface ReporterInterface {
reporter_code: number;
reporter: string;
reporter_iso: string;
reporter_iso_2?: string;
}
我使用一个服务填充两个数组,但我现在需要某种方法来创建一个包含所有现有货币数据的数组,但是另外,在reporter=counter\u currency
中,我还需要reporter\u iso\u 2
代码
我试过玩concat和push,但运气不好
有人有什么建议吗
我现在已经试过了:
testArray: Array<any>;
addCounterIso() {
this.testArray = this.filteredCurrencies.map(c =>
(
{
...c,
reporter_iso_2: this.filteredCountries.find(x = > x.reporter == c.counter_currency).reporter_iso_2
}
));
}
试着这样做:
result = [];
addCounterIso() {
var self = this
this.result = this.currencyArray.map(function(item) {
var reporter = self.reporterArray.find(x => x.reporter == item.counter_currency);
return {
...item,
reporter_iso_2: reporter ? reporter.reporter_iso_2 : null
};
});
}
使用
Map
collection、Map
方法和spread
操作符:
let currencyArray=[
{
货币代码:“A”,
基本货币代码:“B”,
基本货币:“C”,
柜台货币代码:“D”,
对应货币:“欧元”
}
];
让reporterArray=[
{
记者代码:“E”,
记者:“欧元”,
记者(iso):"F",,
记者(2):"G"
},
{
记者代码:“J”,
记者:“卢比”,
记者(iso):"L",
记者(2):"M"
}
];
const currencyMap=新映射(currencyArray.Map(o=>[o.counter\u currency,o]);
const result=reporterArray.map(a=>({…a,…currencyMap.get(a.reporter)}));
控制台日志(结果)
@Adrita Sharma的答案当然有效,但它是O(n2)(假设Javascript的Array.prototype.find()
需要O(n))
但是,如果您确信您的计数器货币
/报告器
是唯一的,那么您可以首先在计数器货币
/报告器
上对这两个数组进行排序,这两个数组的值都大约为O(logn)。然后通过只遍历货币
数组一次来合并它们。最后大概是O(n logn)
注意:仅当
计数器货币
/报告器
唯一且可排序时才起作用。能否显示一些演示?能否将源数据显示为文本,将所需数据显示为文本?显示此.filteredcurrences
和此.filteredCountries
。控制台并显示输出您可以在stackbiltz中共享它,我认为是其他原因导致了错误。不幸的是,这会导致我出现“没有重载匹配此调用”错误,因此我将继续玩下去