Apply _.set with _.each in lodash

时间:2016-02-12 20:14:49

标签: javascript lodash

I want to be able to set a property on all objects inside of an array like this:

height: calc(~'100% ' - (@site-navbar-height + @site-menubar-height));

I tried to accomplish this by using var items = [{ a: 1 }, { a: 2 }, { a: 3 }]; _.each(items, set('a', 4)); // result should be [{ a: 4 }, { a: 4 }, { a: 4 }] on _.rearg to change the parameter that takes the object to the last one like this:

_.set

However, I cannot get var set = _.rearg(_.set, [2, 0, 1]); to work on top of calling _.curry.

_.rearg

So the desired result of being able to call it like this var set = _.curry(_.rearg(_.set, [2, 0, 1])); set('a', 3, { a: 4 }) // returns Object {a: 3} correctly set('a', 3) //returns undefined, should be a function throws an error because it does not return a function.

How do I accomplish this using lodash? I must be missing something.

4 个答案:

答案 0 :(得分:1)

if your items is

static String[] animal={
        "animale",
        "animale2",
        "animale3",

};

static int[] animal_id={
        R.raw.a11_ovation,


};

then for lodash _.each and _.set, it would be like this

var items = [{ a: 1 }, { a: 2 }, { a: 3 }];

what you are trying to do is, looking up a property 4 on item a, where it doesn't know when a is or 4 is. hope it helps.

答案 1 :(得分:1)

The _.curry function accepts an argument MailItem.PropertyAccessor.SetProperty("MailItem.PropertyAccessor.SetProperty", false) that you should probably set to arity:

3

Creates a function that accepts arguments of _.curry(func, [arity=func.length]) and either invokes func returning its result, if at least func number of arguments have been provided, or returns a function that accepts the remaining arity arguments, and so on. The func of func may be specified if arity is not sufficient.

The result from func.length has a length value of zero but the underlying function requires three parameters, so you will need to specify that manually:

_.rearg

Here's a live demo: http://codepen.io/anon/pen/qbgmPq

答案 2 :(得分:0)

Iterating through the list of items and using _.set on each item works.

[autorun]
open=index.html

or

_.map(items,function(item){_.set(item,'a',5)});

Codepen

答案 3 :(得分:0)

rearg()的问题出现在六个月后你必须阅读你的代码时 - 破译参数位置很麻烦。结合unary()partialRight()可以提供更清晰的意图:

_.each(items, _.unary(_.partialRight(_.set, 'a', 4)));