9

I am trying to get from here:

example = [{
  name: "someone1",
  city: "somewhere1",
  state: "someplace1"
},{
  name: "someone2",
  city: "somewhere2",
  state: "someplace2"
}]

to here:

example.name = [ "someone1", "someone2" ]

In as little a code as possible. Obviously I could just loop it and build the array but I need to do this a large number of times on a variety of objects. I could write a function to do it but it would be difficult to make the function general enough for my application.

Is there a shortcut for this in jQuery?

  • You have to use jquery loop. I hope this will help to you dear. stackoverflow.com/questions/2342371/… – Deep Kakkar Apr 6 '15 at 13:55
  • 1
    Native javascript is always going to be faster than jQuery. – m0meni Apr 6 '15 at 13:56
  • explain a bit more.. you have one object, that is an array of same objects and then..? – Legends Apr 6 '15 at 13:57
  • 3
    @DeftSoftInformatics No, one doesn't have to. – undefined Apr 6 '15 at 13:59
9

You can iterate through the object keys and save the name in the array using push:

example = [{
  name: "someone1",
  city: "somewhere1",
  state: "someplace1"
}, {
  name: "someone2",
  city: "somewhere2",
  state: "someplace2"
}];
var arrNames = [];
//iterate through object keys
Object.keys(example).forEach(function(key) {
  //get the value of name
  var val = example[key]["name"];
  //push the name string in the array
  arrNames.push(val);
});
console.log(arrNames);//prints ["someone1", "someone2"]

After @Felix suggestion(with which I agree) there is no need to use Object.keys:

example = [{
  name: "someone1",
  city: "somewhere1",
  state: "someplace1"
}, {
  name: "someone2",
  city: "somewhere2",
  state: "someplace2"
}];
var arrNames = [];
//iterate through object keys
example.forEach(function(item) {
  //get the value of name
  var val = item.name
  //push the name string in the array
  arrNames.push(val);
});
console.log(arrNames); //prints ["someone1", "someone2"]

References

Object.keys()

Array.prototype.forEach()

Array.prototype.push()

| improve this answer | |
  • 2
    Just made a generic function of this taking the object name and key names and it works flawlessly. Great answer, thank you! – awimley Apr 6 '15 at 14:20
  • Object.keys(example).forEach(function(key) { is a very strange way to iterate over an array. Why not simply example.forEach(function(item) { ... })? – Felix Kling Jul 13 '15 at 11:28
  • Thanks @FelixKling for the feedback. You are right. I will update my answer later. – Alex Char Jul 13 '15 at 11:48
  • How to get this to create an array of values like ["someone1", "somewhere1","someplace1"],[...] and so on? – JackTheKnife Jun 12 '18 at 13:38
7

I made a quick test for you here: http://jsperf.com/jquery-vs-javascriptlvjsklvjsfklsfklsdjfk

It consists of three solutions:

A basic for loop

for (var i = 0; i < example.length; i++) {
    array.push(example[i].name);
}

A jQuery $.each()

$.each(example, function(i, item) {
    array.push(example[i].name);
});

And one answer posted to this thread

Object.keys(example).forEach(function(key) {
  //get the value of name
  var val = example[key]["name"];
  //push the name string in the array
  array.push(val);
});

Here are the results (bigger bar is better)

Basically what you have to keep in mind is that jQuery might have a shortcut which consists of "less code", but in reality it'll have worse performance than if you wrote the code yourself.

| improve this answer | |
  • Though forEach is the slowest, I'm not worried about speed and it allows me to do this for all properties I need with one loop (by not having return statements). Thank you for your input; I chose to use forEach as it is the fastest to write for my application. – awimley Apr 6 '15 at 15:21
  • This is the best answer to the question tho! You could improve the loop better by checking the length once at the begging and storing it as a local var rather than checking with each loop cycle. i.e. for (var i = 0, x = example.length; i < x; i++) – firefields Jan 10 '17 at 13:59
6

You can use the $.map function from jQuery :

var value = $.map(example, function () {
    return this.name;
});

This will return an array of the items.

| improve this answer | |
  • This answer works but the one below was accepted because it can do all the property names I need at the same time. +1 – awimley Apr 6 '15 at 14:22
2

Here is how to do it using jinqJs

The line of code is:

jinqJs().from(example).select(function(row){return row.name;});

var example = [{
  name: "someone1",
  city: "somewhere1",
  state: "someplace1"
},{
  name: "someone2",
  city: "somewhere2",
  state: "someplace2"
}];

var result = jinqJs().from(example).select(function(row){return row.name;});

document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 2) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.min.js"></script>

| improve this answer | |
1

This is the simplest solution I can think of:

function doThat (myArray) {
  newObject = {};
  myArray.forEach(function (obj, idx) {
    var keys = Object.keys(obj);
    keys.forEach(function (key) {
      if (!obj[key]) {
        newObject[key] = [];
      }
      newObject[key][idx] = obj[key]; 
    });
  });
  return newObject;
}
| improve this answer | |
  • I think my solution is more generic since it keeps all the indexes as they were even if one of the objects in the array missed a property – Aleuck Apr 6 '15 at 14:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.