I have requirement like need to form object as below
[
{
"place": "Royal Palace, Oslo",
"latitude" : "59.916911"
},
{
"place": "Royal Palace, Oslo",
"latitude" : "59.916911"
}
]
the above place and latitude values are available within map function as
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();
})
thanks in advance.
Mörre
5,7536 gold badges41 silver badges68 bronze badges
asked Nov 19, 2017 at 11:58
Venuu Munnuruu
3251 gold badge7 silver badges18 bronze badges
-
2What is the question exactly ?3Dos– 3Dos2017年11月19日 12:00:58 +00:00Commented Nov 19, 2017 at 12:00
-
"How do I push an object into an array" is a little too basic for an SO question. The answer is: "Just do it." I mean, you even wrote the desired target array format down already. Weird question... Also, I fail to see any connection to "react" or "react-native" - I removed those tags.Mörre– Mörre2017年11月19日 12:04:54 +00:00Commented Nov 19, 2017 at 12:04
3 Answers 3
You are using the map function wrong. In a map function, you create a new array in which for each value the return value replaces the current value. Your function isn't returning new values, and isn't pushing anything to the array. So you have 2 options:
//FIRST OPTION
const sampleArray = jsonResponse.map(({ place } => ({
place,
latitude: [SOME_VALUE]
}))
//SECOND OPTION
const sampleArray = [];
jsonresponse.forEach(({ place }) => {
sampleArray.push({
place,
latitude: [SOME_VALUE]
})
})
Also, notice the es6 destructuring syntax, it could save you some code.
answered Nov 19, 2017 at 12:05
Gilad Bar
1,3428 silver badges17 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
All you need to do with Array.prototype.map is:
let sampleArray = jsonresponse.map((item) => {
let place = item.place;
let latitude = {/*with other logic function we will get latitude value*/}
return {
place,
latitude
}
})
answered Nov 19, 2017 at 12:21
dfsq
193k26 gold badges244 silver badges261 bronze badges
Comments
Is this what you want to accomplish ?
let sampleArray = []
jsonresponse.map(item => {
sampleArray.push({
place: item.place,
latitude: {/*with other logic function we will get latitude value*/}
})
})
console.log(sampleArray)
answered Nov 19, 2017 at 12:03
3Dos
3,5474 gold badges26 silver badges40 bronze badges
1 Comment
Mörre
@VenuuMunnuruu Look at the other responses, don't use
map for this! 3Dos just asked to clarify what you want, you should not actually do what you did.lang-js