简体   繁体   English

使用underscore.js获取对象作为输出

[英]Get an object as an output using underscore.js

I am trying to use underscore.js on a simple object: 我试图在一个简单的对象上使用underscore.js:

var tab = {
    1: "obj1",
    4: "obj4",
    8: "obj8"
};

What I want to do is simply remove the elements with a key value higher than n so what I did is: 我想做的就是简单地删除键值大于n的元素,所以我要做的是:

function trimFrom(obj, n){
    return _(obj).filter(function(el, id){
        return id <= n;
    });
};

var tab2 = trimFrom(tab, 5)

Now, what I am expecting when I display tab2 is: 现在,当我显示tab2时,我期望的是:

tab2: Object
 1: "obj1",
 4: "obj4"

But what I am getting is: 但是我得到的是:

tab2: Array[2]
 0: "obj1"
 1: "obj4"

How do you get your output to stay as an object and is there any method to apply directly the result to the object passed as a parameter without having to do something like var tab = trimFrom(tab, 5) and avoid copying the values? 如何使输出保持为对象,是否有任何方法可以将结果直接应用于作为参数传递的对象,而不必执行var tab = trimFrom(tab, 5)并避免复制值?

Edit: For those who want to make changes directly on the passed object like me, simply do: 编辑:对于那些想要像我一样直接在传递的对象上进行更改的人,只需执行以下操作:

function trimFrom(obj, n){
    for(var key in obj)
        if(key > n)
            delete obj[key];
};

ou could get the object keys, and use .reduce() to reduce the key/values to a new object. 您可以获取对象键,并使用.reduce()将键/值减少为一个新对象。

DEMO: http://jsfiddle.net/ubxE5/2/ 演示: http : //jsfiddle.net/ubxE5/2/

function trimFrom(obj, n){
    return _.reduce(obj, function(res, val, key){
        if (key <= 5)
            res[key] = val;
        return res
    }, {});
};  //  ^--- the new object

So then you can pass the object in if you like as well. 因此,如果您愿意,也可以传入对象。

function trimFrom(obj, n, result){
    return _.reduce(obj, function(res, val, key){
        if (key <= 5)
            res[key] = val;
        return res
    }, result);
};  //  ^--- the new object



var new_obj = {};

trimFrom(tab, 5, new_obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM