15

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?

awimley
  • 692
  • 1
  • 9
  • 29

5 Answers5

11

You can use the $.map function from jQuery :

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

This will return an array of the items.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Sherif Ahmed
  • 1,896
  • 1
  • 19
  • 37
  • 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 06 '15 at 14:22
11

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()

Alex Char
  • 32,879
  • 9
  • 49
  • 70
  • 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 06 '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
8

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.

m0meni
  • 16,006
  • 16
  • 82
  • 141
  • 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 06 '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++) – Rob Sutcliffe Jan 10 '17 at 13:59
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>
NYTom
  • 524
  • 2
  • 14
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;
}
Aleuck
  • 294
  • 1
  • 12
  • 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 06 '15 at 14:42