JavaScript loop through an array of objects

Is there a way to loop through and retrieve all of the addresses?

const name = {
  john: [
    {
      age: 21,
      address: 'LA',
    }
  ],
  sam: [
    {
      age: 26,
      address: 'California'
    }
  ]
}

I have tried using this code, but I'm still unsure of how it functions

const array = Object.entries(name);
for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

Answer №1

UPDATED ANSWER

If the ObjectValue contains multiple arrays, the following code demonstrates how to extract all addresses and combine them into a single array. Comments are provided within the code for better understanding.

const name = { john: [ { age: 21, address: 'LA', }, { age: 23, address: 'Franch', } ], sam: [ { age: 26, address: 'California' }, { age: 24, address: 'Swiss' } ] }

var ObjectValues = Object.values(name);

// Apply map method to ObjectValue to extract all addresses
var result = ObjectValues.map((ObjectValue) => {
    return ObjectValue.map(item => item.address);
});

// Combine all child arrays into a single array
result = [].concat.apply([], result);

console.log(result);

Using forEach loop to extract all addresses into a single array

const name = { john: [ { age: 21, address: 'LA', }, { age: 23, address: 'Franch', } ], sam: [ { age: 26, address: 'California' }, { age: 24, address: 'Swiss' } ] }

var ObjectValues = Object.values(name);
var result = [];

ObjectValues.forEach((ObjectValue) => {
  ObjectValue.map(item => result.push(item.address));
});

console.log(result);

Creating a function for best practice

const name = { john: [ { age: 21, address: 'LA', }, { age: 23, address: 'Franch', } ], sam: [ { age: 26, address: 'California' }, { age: 24, address: 'Swiss' } ] }

console.log(getAddress(name));

function getAddress(data) {
  let result = []; // initialize storage
  
  Object.values(data).forEach(ObjectValue => {
      ObjectValue.map(item => result.push(item.address));
  });
  return result; // return extracted addresses
}

OLD ANSWER

Object.entries returns arrays of Objects in [key, value] pairs. To extract only the "value" list of an object, use Object.values instead.

After extracting all value lists using Object.values, you can then use either map or forEach method to retrieve all addresses.

const name = {
  john: [
    {
      age: 21,
      address: 'LA',
    }
  ],
  sam: [
    {
      age: 26,
      address: 'California'
    }
  ]
}

var ObjectValues = Object.values(name);

// Using map method to extract addresses
var result = ObjectValues.map(ObjectValue => ObjectValue[0].address);

console.log(result) // Check the extracted addresses

// Using forEach method
var result = []

ObjectValues.forEach(ObjectValue => result.push(ObjectValue[0].address));

console.log('With forEach method')
console.log(result)

Answer №2

If the variable name in your situation is behaving more like a hash map with string keys (such as john and sam) rather than numerical keys (0, 1, 2, etc.), then using Object.entries() will return key-value pairs. This is why using array[i] does not work as expected.

To resolve this issue, you can slightly modify the loop as shown below:

const array = Object.entries(name);

for (const [key, value] of Object.entries(array)) {
  console.log(`${key}: ${value}`);
  // This will log john: [object Object] and sam: [object Object]
}

Answer №3

Here's the solution for you,

Extracting addresses from an object called name using Object.values method and mapping it to get only the address values: 
Object.values(name).map(([{address}])=>address) // ["LA", "California"]

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

Highlight a pair of words in a phrase using jquery technology

Only one word in my code is highlighted $(document).ready(function() { let firstword = 'web'; let secondword = 'js'; $(".field.ConditionsAccept>.caption:contains('" + secondword + "'):contains('" + firstword ...

JavaScript: protecting data, revealing functionality

Looking to enhance my understanding of Javascript basics in order to delve into client-side frameworks like Knockout and Angular, as well as make headway in learning Node.js. I've selected a simple problem used in teaching C# and am now attempting to ...

The latest URL is not launching in a separate tab

Looking for some assistance with this code snippet: <b-btn variant="primary" class="btn-sm" :disabled="updatePending || !row.enabled" @click="changeState(row, row.dt ? 'activate' : 'start&apo ...

Using Nuxt and Cloudinary to seamlessly upload images from the client side directly to the Cloudinary platform

Is there a way to directly upload images from my Nuxt (vue) app to Cloudinary without involving a server? I've been searching for information on how to accomplish this but haven't found any concrete solutions. <v-file-input v-else ...

Fixed width for the last column in DataTables

Here's the scenario: I have a jQuery script that loads DataTables, and I know how to set the "aoColumns" : "sWidth" parameter to fix the width of a specific column, which is working fine. However, my issue arises from having multiple tables with var ...

Manipulating object information within a nested for loop

I have a variable called jobs in my scope, which is an array containing objects for each department along with their respective data. [ “Accounting”: { “foo” : “foo”, “bar” : "bar" }, “Delivery”: { ...

Is there a way to extract individual values from a for-each loop in JavaScript?

Would appreciate any guidance on my use of Bootstrap vue table with contentful's API. I'm currently working on implementing a for loop to iterate through an array and retrieve the property values. Although the console.info(episodes); call success ...

Updating AngularJS views based on window resizing

I've been working on an Angularjs application and everything is running smoothly, but I'm facing challenges when it comes to implementing a mobile version of the site. Simply using responsive styles won't cut it; I need to use different view ...

Display radio buttons depending on the selections made in the dropdown menu

I currently have a select box that displays another select box when the options change. Everything is working fine, but I would like to replace the second select box with radio buttons instead. Can anyone assist me with this? .sub{display:none;} <sc ...

Leveraging dynamic visuals for your Twitter metadata image

My Twitter application automatically posts the current title being broadcast on my web radio every 20 minutes. It includes details like the artist, number of listeners, and playlist, but does not display album covers. To work around this limitation, I am ...

What is the best way to navigate through a complex array in React that includes objects and nested arrays?

I have been working on a JavaScript array that includes subobjects with arrays nested in them. My goal is to iterate through the entire parent object using React. Although I attempted the following approach, unfortunately it did not yield the desired outco ...

Retrieve worldwide data for the entire application in Next.js during the first page load

Within my Next.js application, I am implementing search filters that consist of checkboxes. To display these checkboxes, I need to retrieve all possible options from the API. Since these filters are utilized on multiple pages, it is important to fetch the ...

having trouble transferring the password field in PHP to phpMyAdmin

My HTML form collects the user's first name, last name, username, and password. I am trying to upload this data to my local phpMyAdmin, but I'm facing an issue with storing the password in the database. Below is my HTML code: <input type="te ...

Errors encountered: Navigation guard causing infinite redirection due to unhandled runtime issue

My Vue3 router is set up with the following routes: export const routes: Array<RouteRecordRaw> = [ { path: "/", name: "Browse Questions", component: HomeView, meta: { access: "canAdmin", }, ...

Encountering a problem when looping through a JSON response

After making an Ajax call, I received the JSON response below. studentList: { "currentStudent":0, "totalStudent":11, "studentDetails": [{ "adId":1, "adName":"BMB X5", "sfImage":{ "imageName":"Desert", "image ...

Setting an action when clicking on a slice of a Doughnut chart using Chart.js

I have been working on integrating chart.js into my Django Project, and so far it has been going smoothly. I successfully created a doughnut chart with two slices. Now, I am trying to implement separate actions for each slice when clicked, such as redirect ...

Requesting for a template literal in TypeScript:

Having some trouble with my typescript code, it is giving me an error message regarding string concatenation, const content = senderDisplay + ', '+ moment(timestamp).format('YY/MM/DD')+' at ' + moment(timestamp).format(&apo ...

Protecting Node.js Files

As I prepare to embark on creating a new website, my main goal is to collect form input values such as dropdowns and radio boxes from the client without requiring user accounts. These values will be used for sensitive calculations, making security a top pr ...

Retrieve vuex state in a distinct axios template js file

I have encountered an issue with my Vue project. I am using Vuex to manage the state and making axios requests. To handle the axios requests, I created a separate file with a predefined header setup like this: import axios from 'axios' import st ...

JavaScript closures and the misinterpretation of returning values

function generateUniqueCelebrityIDs(celebrities) { var i; var uniqueID = 100; for (i = 0; i < celebrities.length; i++) { celebrities[i]["id"] = function () { return uniqueID + i; }; }; return celebrities; ...