What is the method for creating an array from an object?

I am facing a challenge with an object that has keys containing an index after the underscore. I need to gather each pair of keys with the same index together in order to achieve my expected object. Can someone help me figure out how to accomplish this using either Underscore.js or plain JavaScript?

var obj = {
        phoneNumber_0 : "2",
        phoneNumber_1 : "0",
        phoneType_0 : "Home",
        phoneType_1 : "Work"
}


var expected = [
  {number: '2', type: 'home'},
  {number: '0', type: 'work'},
]

Answer β„–1

To efficiently organize the keys of an object by name and index, consider splitting them and creating a new object to store the values accordingly.

var obj = { phoneNumber_0: "2", phoneNumber_1: "0", phoneType_0: "Home", phoneType_1: "Work" },
    finalResult = [];

Object.keys(obj).forEach(function (key) {
    var parts = key.split('_');
    finalResult[parts[1]] = finalResult[parts[1]] || {};
    finalResult[parts[1]][parts[0]] = obj[key];
});

console.log(finalResult);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer β„–2

It seems like this code snippet might be the solution you've been seeking:

var obj = {
        phoneNumber_0 : "2",
        phoneNumber_1 : "0",
        phoneType_0 : "Home",
        phoneType_1 : "Work"
}
var finalArray = []
Object.keys(obj).map((key,index) => {
  if (obj['phoneNumber_' + index] || obj['phoneType_' + index])
  finalArray.push({ number: obj['phoneNumber_' + index], type:obj['phoneType_' + index]})
})

console.log(finalArray)

Answer β„–3

Your anticipated outcome will be as follows:

let data = {
  phoneNumber_0 : "6",
  phoneNumber_1 : "3",
  phoneType_0 : "Mobile",
  phoneType_1 : "Office"
}

let expectedResults = []
for(let item in data){
  if(item.indexOf('phoneNumber_') === 0){
    let num = item.replace('phoneNumber_', '')
    expectedResults.push({number: data[item], type: (data['phoneType_' + num] || '').toLowerCase()})
  }
}

console.log(expectedResults)

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

Error: Unable to retrieve data due to null value (property 'detail' is undefined)

When I use useEffect() function to set the document title to 'View Orders | Bothub' and fetch data from a backend URL, I encounter an error. The error message reads: Unhandled Rejection (TypeError): Cannot read properties of null (reading 'd ...

transforming JSON information into tables on a webpage

Can someone help me with the challenge of incorporating a massive JSON file into an HTML table? I am encountering an issue where I continuously receive the error message Uncaught TypeError: v.forEach is not a function. Any guidance would be greatly appreci ...

Error message: Attempting to access index 0 of an undefined property within a Vue.js v-for loop

The return of console.log(this.sights) is an array containing 20 objects, each with properties such as name, photos, references, etc. My current goal is to iterate through these objects, displaying their names and photo_references. Here is how I am attempt ...

Generate unique links for each individual object

I am dealing with an array of objects that look like this: const myData = [ { "image": "https://placedog.net/300?random", "name": "A", }, { "image": "https://placedog.net/300?random&q ...

Retrieve the variable declared within the event

How can I access a variable set in an event? Here is the code snippet: $scope.$on('event_detail', function (event, args) { $scope.id = args; console.log($scope.id); // This prints the correct value }); console.log($scope.id); // ...

Aggregating MongoDB: Calculating unique values within an array

Looking to find the distinct tags count on all records within a mongodb query, utilizing JS. Data structure of the record: { "_id": { "$oid": "62e593aed8fd9808777225e8" }, "title": "β€œThe world as ...

What methods can I employ with JavaScript to catalog data collected from an HTML form?

Currently, my form requires users to input a username that cannot start or end with a period (.). I have implemented some code but I believe there is an issue with the .value[0] parts. //Checking Username if (document.getElementById("uName&quo ...

I am looking to modify the JSON format of the API response

Received this response from the API and need to convert the JSON format below: Original: "data": [ [ { "isFile": "true", "fileType": "image", "filesize": 100793, ...

Is there a way to input the Sno data into the database in ascending order?

function table_insert(lease_ids){ var lease_id=lease_ids+1; var table = document.getElementById('table_data123'), rows = table.getElementsByTagName('tr'), i, j, cells, customerId; for (i = 0, j = rows.le ...

Design of Redux middleware with focus on return values

I just finished learning about redux middleware, and it seems really useful. However, I have a question regarding the return values of middleware. I understand that some middleware return values (such as redux-promise), while others like logging do not - ...

When integrating the React custom hook setValue into another component, it appears to be returning an undefined

I have created a custom useLocalStorage hook. When I directly use it in my component and try to update the value, I encounter an error stating that setValue is not a function and is actually undefined. Here's the code snippet: // Link to the original ...

When functions are called, JavaScript variables can sometimes disappear within them

Currently, I am facing an issue within my Google Maps code that is actually stemming from an architectural problem. Due to a high volume of requests, Google Maps sometimes limits the response, prompting the need for an additional request with a delay. Ho ...

Ways to access the attribute of the element being hovered over

So, I am currently attaching event listeners to an array of elements with the intention that when a specific element is hovered over, it will set a property to the id of that element. However, instead of grabbing the id of the hovered element, it seems to ...

The sequence of initializing test hooks in inconsistent playwright tests

My testing framework setup looks something like this: test.describe("...", () => { let p: Page; test.beforeEach(async({browser}) => { p = await (await browser.newContext()).newPage(); } test(...); test(...); test.aft ...

Error encountered when processing a PUT request for a node causing a

After receiving minimal views and replies on a similar question I posted last night, I am reaching out again in hopes of resolving my issue. For the past two days, I have been struggling to fix this problem and progress with my project! If you are interes ...

Tips for sending an Ajax request to a separate URL on the same server

When making an ajax request to my server, I use the following code: var data = ''; $.ajax({ type: 'GET', url: 'api/getnews/home/post/'+title, data: data, datatype: 'json', success: f ...

JavaScript creates dynamic three.js animations on top of an image

When you visit the link above, you will see an animation of stars and a sphere reflecting that animation. My goal is to have https://i.sstatic.net/VpxWH.png It would mean that the reflective sphere is displayed on the astronaut's helmet. I am strug ...

Is there a way to eliminate the legend symbol for just one legend in Highcharts?

Looking to customize a legend in Highcharts but facing limitations due to Plot Lines and Bands not having legends. To work around this, I have added an empty series that acts as a toggle for showing/hiding plot lines. Since my plot lines are vertical, I im ...

Tips on removing properties from an object recursively according to their key/value pairs

My current task involves removing specific children of an object based on whether their "size" key is set to 0. To achieve this, I am utilizing the npm package directory-tree to generate a JavaScript object representation of a chosen directory. The stru ...

How to implement various middlewares in Express.js depending on the current environment using NODE_ENV?

My dilemma involves utilizing two different middlewares based on NODE_ENV: router1 for production and router2 for testing and development environments. I'm currently using the following code snippet: if( process.env.NODE_ENV === 'prod' ) { ...