1

I have an object like this:

customers:
{
  239:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  },
  242:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  },
  etc...
}

How can I iterate to get all firstnames, preferably using jQuery? The numbered ID's are not necessarily in sequence.

4
  • $.each(customers, function(index, item) { console.log(item.firstname);}); Commented Nov 24, 2015 at 12:05
  • 1
    @fuyushimoya .map works with array Commented Nov 24, 2015 at 12:09
  • Thx for point it out. Commented Nov 24, 2015 at 12:10
  • @fuyushimoya, I like your solution. Simple and easy to understand. Please make it an answer, so that I can make it the "Accepted answer" :) Commented Nov 24, 2015 at 12:24

3 Answers 3

2

To loop over an object, and get each subobject's item, you can use the $.each to achieve that, for example:

var customers = {
  239:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  },
  242:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  }
};

var firstnamesInArray = [],
        firstnamesInObject = [];

// The $.each requires an object/array as first param, and a function as second param.
// And it'll iterate through the object and call the passed in function with (key, value).
$.each(customers, function(index, item) {
  // So at here, you'll get, for example: index as 239, and item as {firstname: "Peter", lastname: "Johnson"}.
  
  // Do anything with the sub item.
  console.log(item.firstname);
  
  // You can also get the targets to arrayform or object form.
  firstnamesInArray.push(item.firstname);
  firstnamesInObject[index] = item.firstname;
});

console.log("Get into array:", firstnamesInArray);
console.log("Get into object:", firstnamesInObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

0

var data = {customers:
{
  239:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  },
  242:
  {
    firstname : "Peter",
    lastname  : "Johnson"
  }
}};


$.each(data,function(k,v){
  $.each(v,function(key,value){
    console.log(key+"    "+value.firstname);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can do it like with this in the jquery

Comments

0

var customers = {
    239: {
        firstname: "Peter",
        lastname: "Johnson"
    },
    242: {
        firstname: "Paul",
        lastname: "Johnson"
    },
};

var firstnames = Object.keys(customers)
    .reduce((p, c) => 
        p.push(customers[c].firstname) && p, []);

document.write(firstnames.join(', ')); // "Peter, Paul"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.