我可以使用lodash用另一个数据更新数组吗?

时间:2014-01-14 05:06:05

标签: javascript lodash

我有一个名为grid.data的数组,它有一个assignedTo字段,在这个例子中是一个Id值(25和26)。我还有另一个名为userProfiles的数组,它有一个id和一个名字字段。

var grid.data = [
   {"cityId":9,"assignedTo":"25"},
   {"cityId":63,"assignedTo":"26"}];

var userProfiles = [
   {"id":"25","name":"john"},
   {"id":"26","name":"jacky"}];

我有以下功能:

var getUser = function (userId) {
    if (userId && userProfiles)
        for (var i = 0; i < userProfiles.length; i++)
            if (userProfiles[i].id === userId)
                return userProfiles[i].name;
    return '';
}

我是否可以使用_lodash来调用getUser函数 assignedTo值并将assignedTo替换为用户名 那回来了吗?或者(如果这是一种更好的方式),我可以将grid.data和$ scope.option.userProfiles与_lodash结合使用,并避免调用getUser吗?

这是我需要的输出:

var grid.newData = [
   {"cityId":9,"assignedTo":"john"},
   {"cityId":63,"assignedTo":"jacky"}];

2 个答案:

答案 0 :(得分:0)

您可以合并_.map_.where ....

grid.newData = _.map(grid.data, function(item) {
    var profile = _.where(userProfiles, {id : item.assignedTo})[0];
    return {
        cityId : item.cityId,
        assignedTo : profile.name
    }
});

答案 1 :(得分:-2)

你可以用vanilla.js:

来做
var grid_data = [
   {"cityId":9,"assignedTo":"25"},
   {"cityId":63,"assignedTo":"26"}];

var userProfiles = [
   {"id":"25","name":"john"},
   {"id":"26","name":"jacky"}];

var output = []

// loop over the grid data and the user profiles.
for(var o = 0, olen = grid_data.length; o < olen; ++o) {
  for(var i = 0, ilen = userProfiles.length; i < ilen; ++i) {

    // skip pairs that don't match.
    if(grid_data[o].assignedTo !== userProfiles[i].id) {
      continue
    }

    output.push({
      cityId: grid_data[o].cityId,
      assignedTo: userProfiles[i].name
    })
  }
}

console.log(output)
//  [ { cityId: 9, assignedTo: 'john' },
//    { cityId: 63, assignedTo: 'jacky' } ]

或者,如果您更喜欢更实用的方法:

console.log(grid_data.map(join).reduce(flatten, []))

function join(city) {
  return userProfiles.filter(matches).map(merge)

  function merge(profile) {
    return {
      cityId: city.cityId,
      assignedTo: profile.name
    }
  }

  function matches(profile) {
      return profile.id === city.assignedTo
  }

}

function flatten(lhs, rhs) {
  return lhs.concat(rhs)
}

最后lodash(扩展@ el_bob的回答)

var _ = require('lodash')

console.log( _.flatten(_.map(grid_data, function(city) {
  return _.map(_.where(userProfiles, {id : city.assignedTo}), merge)

  function merge(profile) {
    return {
      cityId: city.cityId,
      assignedTo: profile.name
    }
  }
})))