Chris
Chris

Reputation: 3705

Efficient way to change object key names

I am trying to change object key names to something different. Like "name => text, _id => value"

I tried the following which works fine. I was wondering whether there is better ways to do that?

var a = {
    name: "Foo",
    _id: "1234"
};

var b = {
    name: "bar",
    _id: "222"
};

var map = {
    name: "text",
    _id: "value",
};

var arr = [a, b];
var arr2 = [];

_.each(arr, function (obj) {
    obj = _.reduce(a, function (result, value, key) {
        key = map[key] || key;
        result[key] = value;
        return result;
    }, {});

    arr2.push(obj);
});

console.log(arr2);

JSFiddle

Upvotes: 0

Views: 74

Answers (1)

ntalbs
ntalbs

Reputation: 29438

If the number of properties are only two, you can map them manually.

var arr2 = _.map(arr, function (e) {
  var o = {};
  o[map.name] = e.name;
  o[map._id] = e._id;
  return o;
});

Sometimes, do it manually is cleaner.

If you want to iterate over the properties of given objects, then:

var arr2 = _.map(arr, function (e) {
  var o = {};
  for (k in e) {
    o[k] = e[k];
  }
  return o;
});

Those codes are shorter and more readable than the original ones.

Upvotes: 2

Related Questions