简体   繁体   English

在Javascript中使用索引键值JSON创建新数组

[英]create new array with index key value JSON in Javascript

I have a JSON like this: 我有一个像这样的JSON:

{
  "codeA": {
    "USD": 125.648
  },
  "codeB": {
    "USD": 654.547
  },
  "codeC": {
    "USD": 132.45
  }
}

I populate into new array after API calling success: API调用成功后,我将填充到新数组中:

then(function successCallback(response) {
  var responsePrice = response.data; 
}

I want to populate an array like this: 我想填充这样的数组:

var pricesCode = 
  pricesCode[0].code = codeA;
  pricesCode[0].currency = USD;
  pricesCode[0].price = 125.648;

I am using the jQuery $.each function 我正在使用jQuery $.each函数

$.each(responsePrice, function(key, value) {
    priceCode.push({
        currency: key,
        price: value
    });
});
console.log(priceCode);

but the result I am getting is: 但是我得到的结果是:

 priceCode[currency[0] = codeA, price[0] = USD, object undefined]

Can someone show me right code or similar question as asked before. 有人可以向我显示正确的代码或之前询问的类似问题。 Many thanks. 非常感谢。

You can combine Object.keys() and Array.prototype.reduce() to acheive this. 您可以结合使用Object.keys()Array.prototype.reduce()来达到目的。 Please see following. 请参阅以下内容。

 var responsePrice = { "codeA": { "USD": 125.648 }, "codeB": { "USD": 654.547 }, "codeC": { "USD": 132.45 } } var pricesCode = Object.keys(responsePrice).reduce(function(acc, code) { var currency = Object.keys(responsePrice[code])[0]; var obj = { code, currency, price: responsePrice[code][currency] } acc.push(obj); return acc; }, []) console.log(pricesCode[0].code); console.log(pricesCode[0].currency); console.log(pricesCode[0].price); 

Do this to get a comlete array with the data you want: 这样做以获得包含所需数据的完整数组:

let data = {
    "codeA": {
        "USD": 125.648
    },
    "codeB": {
        "USD": 654.547
    },
    "codeC": {
        "USD": 132.45
    }
};

console.log(
  Object.getOwnPropertyNames(data).map(code => {
    return Object.getOwnPropertyNames(data[code]).map(x => {
      return {
        code,
        currency: x,
        price: data[code][x]
      }
    })
  }).reduce((result, arr) => result.concat(arr), [])  
)

Probably there are many ways to accomplish that, quickly I came up with this: 大概有很多方法可以实现,很快我就想到了:

function gValue (obj){ return obj[Object.keys(obj)]};
function gKey (obj){ return Object.keys(obj)[0]};
var pricesCode = [];

$.each(responsePrice, function (key, obj) 
   {
        pricesCode.push({code: key, currency: gKey(obj), price:gValue(obj) });
   });

Please check the variables name you are using (pricesCode vs priceCode) 请检查您使用的变量名称(pricesCode与priceCode)

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

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