1

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

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 使用assignedTo 值调用getUser 函数并将assignedTo 替换为返回的用户名?或者(如果它是更好的方法),我可以将 grid.data 和 $scope.option.userProfiles 与 _lodash 结合起来,避免调用 getUser 吗?

这是我需要的输出:

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

2 回答 2

1

你可以结合 an_.map和 a _.where....

grid.newData = _.map(grid.data, function(item) {
    var profile = _.where(userProfiles, {id : item.assignedTo})[0];
    return {
        cityId : item.cityId,
        assignedTo : profile.name
    }
});
于 2014-01-14T05:31:30.737 回答
-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
    }
  }
})))
于 2014-01-14T06:01:52.547 回答