Nav*_*n I 223 javascript arrays hashmap
用例
用例是基于提供的字符串或函数将对象数组转换为哈希映射,以评估和使用hashmap中的键作为对象本身的值.使用它的常见情况是将对象数组转换为对象的哈希映射.
码
以下是javascript中的小片段,用于将对象数组转换为哈希映射,由对象的属性值索引.您可以提供一个动态(运行时)评估哈希映射键的函数.希望这有助于将来的任何人.
function isFunction(func){
return Object.prototype.toString.call(func) === '[object Function]';
}
/**
* This function converts an array to hash map
* @param {String | function} key describes the key to be evaluated in each object to use as key for hasmap
* @returns Object
* @Example
* [{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap("id")
* Returns :- Object {123: Object, 345: Object}
*
* [{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap(function(obj){return obj.id+1})
* Returns :- Object {124: Object, 346: Object}
*/
Array.prototype.toHashMap = function(key){
var _hashMap = {}, getKey = isFunction(key)?key: function(_obj){return _obj[key];};
this.forEach(function (obj){
_hashMap[getKey(obj)] = obj;
});
return _hashMap;
};
Run Code Online (Sandbox Code Playgroud)
你可以在这里找到要点:https://gist.github.com/naveen-ithappu/c7cd5026f6002131c1fa
jma*_*777 371
var arr = [
{ key: 'foo', val: 'bar' },
{ key: 'hello', val: 'world' }
];
var result = arr.reduce(function(map, obj) {
map[obj.key] = obj.val;
return map;
}, {});
console.log(result);
// { foo:'bar', hello:'world' }
Run Code Online (Sandbox Code Playgroud)
注意: Array.prototype.reduce()
是IE9 +,因此如果您需要支持旧版浏览器,则需要对其进行填充.
mat*_*scb 251
var arr = [
{ key: 'foo', val: 'bar' },
{ key: 'hello', val: 'world' }
];
var result = new Map(arr.map(i => [i.key, i.val]));
// When using TypeScript, need to specify type:
// var result = arr.map((i): [string, string] => [i.key, i.val])
// Unfortunately maps don't stringify well. This is the contents in array form.
console.log("Result is: " + JSON.stringify([...result]));
// Map {"foo" => "bar", "hello" => "world"}
Run Code Online (Sandbox Code Playgroud)
Fab*_*oli 63
您可以使用新Object.fromEntries()
方法。
例子:
const array = [
{key: 'a', value: 'b', redundant: 'aaa'},
{key: 'x', value: 'y', redundant: 'zzz'}
]
const hash = Object.fromEntries(
array.map(e => [e.key, e.value])
)
console.log(hash) // {a: b, x: y}
Run Code Online (Sandbox Code Playgroud)
spl*_*tor 35
var arr = [
{ key: 'foo', val: 'bar' },
{ key: 'hello', val: 'world' }
];
var result = _.keyBy(arr, o => o.key);
console.log(result);
// Object {foo: Object, hello: Object}
Run Code Online (Sandbox Code Playgroud)
Jas*_*ing 29
list.reduce((obj, item) => ({...obj, [item.name]: item.value}), {})
Run Code Online (Sandbox Code Playgroud)
list.reduce((obj, item) => ({...obj, [item.name]: item.value}), {})
Run Code Online (Sandbox Code Playgroud)
shu*_*kar 25
使用ES6 Spread + Object.assign:
array = [{key: 'a', value: 'b', redundant: 'aaa'}, {key: 'x', value: 'y', redundant: 'zzz'}]
const hash = Object.assign({}, ...array.map(s => ({[s.key]: s.value})));
console.log(hash) // {a: b, x: y}
Run Code Online (Sandbox Code Playgroud)
Ped*_*pes 23
使用传播运算符:
const result = arr.reduce(
(accumulator, target) => ({ ...accumulator, [target.key]: target.val }),
{});
Run Code Online (Sandbox Code Playgroud)
演示jsFiddle上的代码片段.
Jun*_*711 13
您可以使用Array.prototype.reduce()和实际的JavaScript Map而不是JavaScript 对象.
let keyValueObjArray = [
{ key: 'key1', val: 'val1' },
{ key: 'key2', val: 'val2' },
{ key: 'key3', val: 'val3' }
];
let keyValueMap = keyValueObjArray.reduce((mapAccumulator, obj) => {
// either one of the following syntax works
// mapAccumulator[obj.key] = obj.val;
mapAccumulator.set(obj.key, obj.val);
return mapAccumulator;
}, new Map());
console.log(keyValueMap);
console.log(keyValueMap.size);
Run Code Online (Sandbox Code Playgroud)
地图和对象有什么不同?
以前,在使用JavaScript实现Map之前,Object已被用作Map,因为它们具有相似的结构.
根据您的使用情况,如果您需要拥有订购的密钥,需要访问地图的大小或经常添加和删除地图,最好使用地图.
从MDN文档引用:
对象类似于Maps,它们都允许您将键设置为值,检索这些值,删除键,以及检测某些键是否存储在键中.正因为如此(并且因为没有内置替代品),所以对象在历史上被用作地图; 但是,在某些情况下,使用Map更为重要:
小智 9
es2015版本:
const myMap = new Map(objArray.map(obj => [ obj.key, obj.val ]));
Run Code Online (Sandbox Code Playgroud)
正如其他海报所解释的那样,有更好的方法可以做到这一点。但如果我想坚持纯 JS 和老式的方式,那么这里是:
var arr = [
{ key: 'foo', val: 'bar' },
{ key: 'hello', val: 'world' },
{ key: 'hello', val: 'universe' }
];
var map = {};
for (var i = 0; i < arr.length; i++) {
var key = arr[i].key;
var value = arr[i].val;
if (key in map) {
map[key].push(value);
} else {
map[key] = [value];
}
}
console.log(map);
Run Code Online (Sandbox Code Playgroud)
如果要转换为新的 ES6 Map,请执行以下操作:
var kvArray = [['key1', 'value1'], ['key2', 'value2']];
var myMap = new Map(kvArray);
Run Code Online (Sandbox Code Playgroud)
为什么要使用这种类型的 Map?好吧,这取决于你。看看这个。
这就是我在 TypeScript 中所做的我有一个小工具库,我把这样的东西放在里面
export const arrayToHash = (array: any[], id: string = 'id') =>
array.reduce((obj, item) => (obj[item[id]] = item , obj), {})
Run Code Online (Sandbox Code Playgroud)
用法:
const hash = arrayToHash([{id:1,data:'data'},{id:2,data:'data'}])
Run Code Online (Sandbox Code Playgroud)
或者如果您有除“id”以外的标识符
const hash = arrayToHash([{key:1,data:'data'},{key:2,data:'data'}], 'key')
Run Code Online (Sandbox Code Playgroud)
Nav*_*n I -2
以下是我在 javascript 中创建的小片段,用于将对象数组转换为哈希映射,并按对象的属性值进行索引。您可以提供一个函数来动态评估哈希映射的键(运行时)。
function isFunction(func){
return Object.prototype.toString.call(func) === '[object Function]';
}
/**
* This function converts an array to hash map
* @param {String | function} key describes the key to be evaluated in each object to use as key for hasmap
* @returns Object
* @Example
* [{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap("id")
Returns :- Object {123: Object, 345: Object}
[{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap(function(obj){return obj.id+1})
Returns :- Object {124: Object, 346: Object}
*/
Array.prototype.toHashMap = function(key){
var _hashMap = {}, getKey = isFunction(key)?key: function(_obj){return _obj[key];};
this.forEach(function (obj){
_hashMap[getKey(obj)] = obj;
});
return _hashMap;
};
Run Code Online (Sandbox Code Playgroud)
您可以在这里找到要点:https://gist.github.com/naveen-ithappu/c7cd5026f6002131c1fa
归档时间: |
|
查看次数: |
217157 次 |
最近记录: |