【问题标题】:Combining two objects in JavaScript?在 JavaScript 中组合两个对象?
【发布时间】:2019-01-30 17:07:27
【问题描述】:

我有两个 JSON 文件。

一个看起来像这样:

    {
base: "EUR",
date: "2019-01-30",

rates: {

    USD: 1.1429,
    AND MORE....
    ...
    ...

}
}

还有一个是这样的:

{
results: {
USD: {
    currencyName: "United States Dollar",
    currencySymbol: "$",
    id: "USD"
}
}

我想将它们组合在一起并 得到一个看起来像这样的对象:

{
results: {
USD: {
    currencyName: "United States Dollar",
    currencySymbol: "$",
    id: "USD",
    value: 1.1429   <====== the change
}
}

我在这里找不到类似的东西... 不知道如何开始

我从这些链接中获取值:

https://free.currencyconverterapi.com/api/v6/currencies

https://api.exchangeratesapi.io/latest

带有获取功能:

function getdataFromApiAsync() {
  return fetch('https://api.exchangeratesapi.io/latest')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.rates;
    })
    .catch((error) => {
      console.error(error);
    });
}

【问题讨论】:

  • 如何处理那些“还有更多……”的案例?
  • 所以你必须遍历一个并将其添加到另一个......将成为循环......
  • @messerbill 是的。
  • 您发布为“JSON”的内容根本不是 JSON。 There's no such thing as a "JSON Object"
  • 正如 epascarello 指出的那样 - 循环一个并将其添加到另一个。祝你好运。

标签: javascript json react-native


【解决方案1】:

假设您的结果对象有一个类似这样的接口:

{
  [key: string]: {
    currencyName: string;
    currencySymbol: string;
    id: string;
    value?: number;
  }
}

这里的id 始终与rates 对象的键匹配,那么您可能希望遍历此结果对象的values 并从另一个对象的速率中添加一个值,如下所示:

Object.values(results).forEach(result => {
  const value = rates[result.id];
  if (value) {
    result.value = value;
  }
});

【讨论】:

    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多