0

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
2
  • 2
    What is the question exactly ? Commented 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. Commented Nov 19, 2017 at 12:04

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

1 Comment

@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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.