如何将每个对象值从json推入数组?

时间:2019-02-17 23:36:23

标签: javascript jquery

我有一个JSON响应,其键值如下:

....
    "usp-custom-90":"45.45257926613316,9.178168599999935"
....

注意usp-custom-90连字符!

我需要类似的东西(字段不存在,这只是一个例子):

            data.forEach(({fields})=>{
              coordsB.push(
                ...fields['usp-custom-90']
              );
            });

其中coordsB是之前定义的数组。

json为:

],
      "usp-custom-90":"45.47841306255037,9.120865849999973",
      "_links":{  
         "self":[  
            {  
               "href":"https:\/\/www.example.it\/wp-json\/wp\/v2\/posts\/128402"
            }
         ],
         "collection":[  
            {  
               "href":"https:\/\/www.example.it\/wp-json\/wp\/v2\/posts"
            }
         ],
         "about":[  

我需要推送每个"usp-custom-90"的值

完整代码(使用不存在的字段是错误的):

    fetch('https://www.example.it/wp-json/wp/v2/posts?per_page=50&status=publish')
      .then(res => res.json())
      .then(data =>{
        var coordsB = [];
        console.log(data);
        data.forEach(({fields})=>{
          coordsB.push(
            ...fields['usp-custom-90']
          );
        });

2 个答案:

答案 0 :(得分:2)

基于注释中链接的data sample,该结构是一个对象数组,每个对象都包含一个usp-custom-90属性。对于数组的map运算符,这是一个完美的情况。

因此在上面的代码中,这一行将为您完成所有操作。它将创建数组并使用您要查找的所有值填充它。

var coordsB = data.map(x=> x["usp-custom-90"])

答案 1 :(得分:0)

我猜大概是这样。

Object.entries(object).reduce((ac,[k,v],i,a)=>(ac.push(v['usp-custom-90']),ac),[])

从您的粘贴容器中看来,主要对象是一个数组,其中包含对象,这些对象具有您想要的键:

YourMainArray.reduce((ac,d,i,a)=>(ac.push(d['usp-custom-90']),ac),[])

经过测试,可以为您提供:

["45.45257926613316,9.178168599999935", "45.47841306255037,9.120865849999973", "9.924,-84.090", "44.948,9.039", "45.464150416139695,9.1906395499999", "45.651,11.303", "43.83734441524854,7.905822499999999", "45.05926341591318,9.3354875", "44.872988115810074,13.85009094999998", "44.97805886586813,8.895478499999967", "45.472119466144186,9.173527250000006", "45.165,9.183", "41.937,12.441", "45.464993216140186,9.147909499999969", "45.48624411615216,9.16677489999995", "45.209,9.147", "45.464993216140186,9.147909499999969", "41.848264464222716,12.665936949999946", "45.464993216140186,9.147909499999969", "45.46851557705748,9.139416449999999", "44.507,11.314", "36.731,14.873", "36.222,-121.759", "10.093,77.060", "45.454327616134165,9.175796900000023", "45.469282816142574,9.176045000000045"]