Javascript 如何按值从不可变的 js 映射中获取特定对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29124038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:53:05  来源:igfitidea点击:

How do I get a specific object from an immutable js map by value?

javascriptimmutability

提问by sspross

I created an immutable map (with Immutable-JS) from a list of objects:

我从对象列表中创建了一个不可变映射(使用Immutable-JS):

var result = [{'id': 2}, {'id': 4}];
var map = Immutable.fromJS(result);

Now i want to get the object with id = 4.

现在我想用id = 4.

Is there an easier way than this:

有没有比这更简单的方法:

var object = map.filter(function(obj){
 return obj.get('id') === 4
}).first();

回答by blgt

Essentially, no: you're performing a list lookup by value, not by index, so it will always be a linear traversal.

本质上,不:您正在按值而不是按索引执行列表查找,因此它将始终是线性遍历。

An improvement would be to use findinstead of filter:

一个改进是使用find而不是filter

var result = map.find(function(obj){return obj.get('id') === 4;});

回答by Joshua

The first thing to note is that you're not actually creating a map, you're creating a list:

首先要注意的是,您实际上并不是在创建地图,而是在创建列表:

var result = [{'id': 2}, {'id': 4}];
var map = Immutable.fromJS(result);

Immutable.Map.isMap(map); // false
Immutable.List.isList(map); // true

In order to create a map you can use a reviverargument in your toJScall (docs), but it's certainly not the most intuitive api, alternatively you can do something like:

为了创建地图,您可以revivertoJS调用中使用参数(docs),但这肯定不是最直观的 api,或者您可以执行以下操作:

// lets use letters rather than numbers as numbers get coerced to strings anyway
var result = [{'id': 'a'}, {'id': 'b'}];
var map = Immutable.Map(result.reduce(function(previous, current) { 
    previous[ current.id ] = current;
    return previous;
}, {}));

Immutable.Map.isMap(map); // true

Now we have a proper Immutable.js map which has a get method

现在我们有一个合适的 Immutable.js 映射,它有一个 get 方法

var item = Map.get('a'); // {id: 'a'}

回答by eezing

It may be important to guarantee the order of the array. If that's the case:

保证数组的顺序可能很重要。如果是这种情况:

  1. Use an OrderedMap
  2. Do a set method on the OrderedMap at each iteration of your source array
  1. 使用 OrderedMap
  2. 在源数组的每次迭代中对 OrderedMap 执行 set 方法

The example below uses "withMutations" for better performance.

下面的示例使用“withMutations”以获得更好的性能。

var OrderedMap = Immutable.OrderedMap


// Get new OrderedMap
function getOm(arr) {
    return OrderedMap().withMutations(map => {
        arr.forEach(item => map.set(item.id, item))
    })
}

// Source collection
var srcArray = [
    {
        id: 123,
        value: 'foo'
    },
    {
        id: 456,
        value: 'bar'
    }
]


var myOrderedMap = getOm(srcArray)

myOrderedMap.get(123)
// --> { id: 123, value: 'foo' }

myOrderedMap.toObject()
// --> { 123: {id: 123, value: 'foo'}, 456: {id: 456, value: 'bar'} }

myOrderedMap.toArray()
// --> [ {id: 123, value: 'foo'}, { id: 456, value: 'bar' } ]

回答by Anand Dayalan

When using fromJS for array, you'll get List not map. It will be better and easier if you create a map. The following code will convert the result into Immutable map.

将 fromJS 用于数组时,您将得到 List 而不是 map。如果您创建地图会更好更容易。以下代码将结果转换为不可变映射。

  const map = result.reduce((map, json) =>
    map.set(json.id, Immutable.fromJS(json))
  , Map());

Now, you can

现在你可以

   map.get('2');   //{'id': 2}

Note, if the result has nested structure and if that has array, it will be a List with the above code.

请注意,如果结果具有嵌套结构并且具有数组,则它将是具有上述代码的 List。

回答by roadev

With ES2015 syntax(and constants):

使用ES2015 语法(和常量):

const result = map.find(o => o.get('id') === 4);

回答by Reed

Is there already a way thats easier? I don't know. but you can write your own function. Something like this should work:

有没有更简单的方法?我不知道。但是您可以编写自己的函数。这样的事情应该工作:

var myFunc = function(id){

    var object = map.filter(function(obj){return obj.get('id') === id}).first();

    return object;
}

Then you would just do:
var myObj = myFunc(4);

然后你会这样做:
var myObj = myFunc(4);