iteration using underscores in JavaScript

I am currently working on creating an object using underscore and backbone. I have an array of objects, each containing a nested object with different sets of data.

Within the array, data[0] holds the name of a location while data[2] contains the coordinates for that location.

data: Array[3] 0: Objectcol_id: "4" data: "W Hotel Union 
Square" __proto__: Object1: Object2: Objectcol_id: "13"data: "40.736638, -73.988396"

To extract the coordinates and add them to a new array, I am using the following function:

var newarr = _.map(rawData, function (a) { return [a.records[0].data[2].data] });

I then split the array of coordinates and create key-value pairs in a new object to set the latitude and longitude.

var newnewarr = [];

for (i = 0; i < newarr.length; i++) {
  newnewarr[i] = _.map(newarr[i][0].split(","), function(s){ return parseFloat(s);
  });
}

function longlat(lat, long) {
  this.Latitude = lat; this.Longitude = long;
};

var coordinates = [];

for (i = 0; i < newnewarr.length; i++) {
  coordinates[i] = new longlat(newnewarr[i][0], newnewarr[i][1]);
}

Now, my objective is to create an array of objects in the format below:

newarr = [{
   latitude: 40.736638,
   longitude: -73.988396,
   title: "W hotel Union Square"
},
{
   latitude: 40.736638,
   longitude: -73.988396,
   title: "Union Square Park"
}];

I am struggling to achieve this using my existing code. I attempted iterating over the data object but encountered difficulties. Specifically, I am looking to iterate over data[0] and data[2], retrieve those values, and then populate them into an object as described above. Any suggestions or guidance on how to accomplish this would be greatly appreciated!

var newarr = _.map(rawData, function (a) { return [a.records[0].data[2].data] });

Answer №1

If you want to simplify the process, consider utilizing a second _.map() function like this:

var inputArray = [<insert your data here>];

var temporaryArray = _.map( inputArray, function ( item ) { return [item.info[0]] });

var finalArray = temporaryArray.map(function(element) {
    var tempCoordinates = element[2].data.split(",");

    return {
        latitude: tempCoordinates[0],  
        longitude: tempCoordinates[1],
        title: element[0],
    }
});

console.log(finalArray);

Alternatively, if you prefer a one-step approach:

var inputArray = [<insert your data here>];

var finalArray = inputArray.map(function(element) {
    var tempData = element.info[0];
    var tempCoordinates = tempData[2].date.split(",");

    return {
        latitude: tempCoordinates[0],  
        longitude: tempCoordinates[1],
        title: tempData[0],
    }
});

console.log(finalArray);

Remember, choose descriptive names for your arrays!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When modifying a string in React, the edit always somehow ends up at the very tail end

In my ReactJS app, I have a Material-UI input element. Everything is working well except for one issue - when I try to edit the text in the middle of the string, the cursor always jumps to the end of the string after every letter I input. I suspect this m ...

Angular 6 and the intricacies of nested ternary conditions

I need help with a ternary condition in an HTML template file: <div *ngFor="let $m of $layer.child; let $childIndex=index" [Latitude]="$m.latitude" [Longitude]="$m.longitude" [IconInfo]="$childIndex== 0 ? _iconInfo1:$c ...

Is it possible to host multiple React applications on a single port? Currently experiencing issues with running both an Admin panel and the Front side in production mode on the same Node.js API server

Is it possible to host multiple React applications on the same port? I am experiencing issues with running both an Admin panel and a Front side React app in production mode on the same Node.js API server. ...

The FireBase dispatch functionality fails to update the real-time database

Struggling with a realtimeDB issue while using NuxtJS to manage state and send it to the DB. Saving data works fine, but editing results in a 400 BAD Request error. This error also occurs when trying to manually update information within Firebase realtime ...

Searching for subarrays within subarrays in MongoDB queries

Looking to extract a specific unitHouse sub array from my document which is nested within another sub array. Here is the data: { "_id" : ObjectId("5a17d305c438324308bffb19"), "floorRow" : [ { "floorRowNo" : "F1", "floorRowInfo" : "B ...

"JavaScript issue: receiving 'undefined' when trying to retrieve input

This code snippet is for a web app that tracks the number of losses in a game. The problem arises when trying to retrieve the value, which returns undefined. Every time I reference the username variable, it returns undefined. document.addEventListener(&a ...

Display the state of JSON data

There is a piece of data that I want to display on my page. I only need one specific data from the JSON response, but I am not sure how to do it. Can someone help me copy this data to my website? This is the code from json.php <?php $response = c ...

Utilizing jQuery to iterate over dynamically generated elements sharing a common class

Whenever I click a button, numerous div elements are dynamically created. <table> <tbody id="ProductDetail"></tbody> </table> These dynamically created divs have an associated Amount value that is added upon creation. funtion ...

The getSession provided by the getSession function is accessible within getServerSideProps but appears as undefined within the component

Whenever I try to log the session variable inside the Dashboard component, it comes back as undefined. However, when I log it inside the getServerSideProps function, it returns the correct details. Am I missing something here? Objective: My goal is to fet ...

Refresh the current page with jQuery Mobile when it is clicked

I have a multi page template in jQuery Mobile. How can I refresh the current page when clicking on a hyperlink or button? I am using JQM version 1.4.5 Despite trying the code suggested in how to refresh(reload) page when click button in jQuery Mobile, it ...

Problem with custom anchor component in React that needs to perform an action before being clicked

React Component (Custom Anchor) import React from 'react'; class Anchor extends React.Component { onClick = (event) => { // ----------------------------- // send Google Analytics request ...

Creating a customized tooltip without the need for calling $(document).foundation() and using modernizr

I'm facing an issue with initializing the foundation tool-tip without having to initialize everything (such as $(document).foundation()). It seems like a simple task, but I am struggling. I have two questions in mind: (1) How can I utilize new Founda ...

Deleting items from an array of files and directories with PHP

Currently, I am attempting to retrieve a list of directories within a specified path using the scandir method and then removing any files from the resulting array. However, I am encountering issues with my echo statement. The code snippet I am working on ...

What is the best way to refresh the user interface while executing a lengthy operation in AJAX/Javascript?

With a need to call multiple processes in series using synchronous AJAX calls, I aim to display the status of each long-running process upon completion before proceeding to the next. Below is an excerpt from the code that illustrates this concept: var co ...

Encountering an issue with the message "SyntaxError: Unexpected token < in django-jquery-file

I am currently working on implementing django-jquery-fileupload into my project. https://github.com/sigurdga/django-jquery-file-upload However, I encounter an "Error SyntaxError: Unexpected token < " when attempting to click the "start" upload button. ...

Troubleshooting Issue with jQuery replaceWith in Loop

Trying to make it so that when the update button is clicked, the text on the left side becomes an input box: Click the update button and the text on the left will be an input box However, instead of just one input box appearing, all the text on the left s ...

Storing property data outside of the render method in ReactJS is key for efficient

I have encountered an issue while attempting to map data outside of the render method in my function and return it within the render. The mapping error is causing confusion as I am uncertain about its underlying cause. Below is the function responsible fo ...

I am looking to customize the color of my Material UI switch

I am having difficulty changing the color of my Material UI switch based on my preference. I have tried several ways, but have not achieved the desired outcome. const useStyles = makeStyles((theme) => ({ toggle: { '& .Mui-checked': ...

React.js Component Composition Problem

I am attempting to replicate the following straightforward HTML code within a React environment: Traditional HTML <div> Hello <div>child</div> <div>child</div> <div>child</div> </div> React(working ...

Anticipating the completion of post requests

I am currently working on implementing a file upload feature in Angular. I have tackled the issue of file size restrictions by creating an API endpoint that can receive file chunks. Once all the chunks are received, another endpoint needs to be triggered ...