将对象推入数组

时间:2017-11-19 11:58:32

标签: javascript

我需要像下面那样形成对象

[
    {
      "place": "Royal Palace, Oslo",
      "latitude" : "59.916911"
    },
    {
      "place": "Royal Palace, Oslo",
      "latitude" : "59.916911"
    }
]

上述地点和纬度值在地图函数中可用

let sampleArray = [];
jsonresponse.map((item) => {
    let place = item.place;
    let latitude = {/*with other logic function we will get latitude value*/}
    //need to send these both values into below array to form array shown as above.
    sampleArray.push();
})

提前感谢。

3 个答案:

答案 0 :(得分:1)

您正在使用错误的地图功能。 在map函数中,您将创建一个新数组,其中对于每个值,返回值将替换当前值。 您的函数不会返回新值,也不会将任何内容推送到数组中。所以你有两个选择:

//FIRST OPTION
const sampleArray = jsonResponse.map(({ place } => ({
    place,
    latitude: [SOME_VALUE]
}))

//SECOND OPTION
const sampleArray = [];
jsonresponse.forEach(({ place }) => {
    sampleArray.push({
        place,
        latitude: [SOME_VALUE]
    })
})    

另外,请注意es6解构语法,它可以为您节省一些代码。

答案 1 :(得分:1)

您需要对Array.prototype.map执行的操作是:

let sampleArray = jsonresponse.map((item) => {
    let place = item.place;
    let latitude = {/*with other logic function we will get latitude value*/}

    return {
      place,
      latitude
    }
})

答案 2 :(得分:0)

这是你想要完成的吗?

let sampleArray = []
jsonresponse.map(item => {
  sampleArray.push({
    place: item.place,
    latitude: {/*with other logic function we will get latitude value*/}
  })
})

console.log(sampleArray)
相关问题