如何获取每个对象键的 id

l 有以下数据json,包含在对象键上,这些键是定期更改的


  "2461ba4c": [ // <----------- get the main key for each one 

    "4BD436",

    36.346,

    33.478,

  ],

  "2461b87c": [

    "06A128",

    34.628,

    33.584,


  ]

我想为每个数组获取对象的键。


我确实过滤了键.filter(key => key ),但它给了我对象的所有键。我想给每个数组主键对象。


function data() {

  $.ajax('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', {

    type: 'GET',

    dataType: 'jsonp',

    timeout: 5000

  }).done(function(data, textStatus, jqXHR) {

    Object.keys(data)

      .map(key => data[key])

      .map((position) => ({

        lat: position[1],

        lng: position[2],

                        // <----------- Add the main key here for each array

      })).filter(position => position.lat && position.lng).forEach(i => {

        console.log(i.lat, i.lng, i.heading)

      })

  })

}

预期输出:


2461b87c, // <---main key

34.628,

33.584,


胡说叔叔
浏览 101回答 2
2回答

万千封印

您可以在 map 方法中创建一个新的 obj 并分配键值,例如,const dataObj = {&nbsp; &nbsp; lat: position[1],&nbsp; &nbsp; lng: position[2],&nbsp; &nbsp; heading: key&nbsp; }并返回对象。片段如下,const data = {&nbsp; "2461ba4c": [&nbsp; &nbsp; "4BD436",&nbsp; &nbsp; 36.346,&nbsp; &nbsp; 33.478,&nbsp; ],&nbsp; "2461b87c": [&nbsp; &nbsp; "06A128",&nbsp; &nbsp; 34.628,&nbsp; &nbsp; 33.584,&nbsp; ]}const newData = Object.keys(data).map(key => {&nbsp; const position = data[key];&nbsp; const dataObj = {&nbsp; &nbsp; lat: position[1],&nbsp; &nbsp; lng: position[2],&nbsp; &nbsp; heading: key&nbsp; }&nbsp; return dataObj;})newData.filter(position => position.lat && position.lng).forEach(i => {&nbsp; &nbsp; console.log(i.lat, i.lng, i.heading)})

qq_花开花谢_0

我们可以in为此使用循环let arr =&nbsp; {"2461ba4c": [&nbsp;&nbsp; &nbsp; "4BD436",&nbsp; &nbsp; 36.346,&nbsp; &nbsp; 33.478,&nbsp; ],&nbsp; "2461b87c": [&nbsp; &nbsp; "06A128",&nbsp; &nbsp; 34.628,&nbsp; &nbsp; 33.584,&nbsp; ]};&nbsp;&nbsp;for( let a in arr){&nbsp; document.write(a+"<br>");&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript