使用案例
用例是基于提供的字符串或函数将对象数组转换为哈希映射,以评估和使用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;
};
您可以在此处找到要点:https://gist.github.com/naveen-ithappu/c7cd5026f6002131c1fa
答案 0 :(得分:319)
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' }
注意: Array.prototype.reduce()
是IE9 +,因此如果您需要支持旧浏览器,则需要对其进行填充。
答案 1 :(得分:211)
使用ES6 Map(pretty well supported),您可以尝试:
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"}

答案 2 :(得分:32)
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}
答案 3 :(得分:20)
使用点差运算符:
const result = arr.reduce(
(accumulator, target) => ({ ...accumulator, [target.key]: target.val }),
{});
在jsFiddle上演示代码段。
答案 4 :(得分:11)
您可以使用Array.prototype.reduce()和实际的JavaScript Map来代替JavaScript Object。
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);
Map和Object有什么区别?
以前,在JavaScript中实现Map之前,由于对象的结构相似,因此Object被用作Map。
根据您的用例,如果您需要有序的键,需要访问地图的大小或需要频繁从地图中添加和删除地图,则最好使用Map。
引用MDN document:
对象与Maps相似,两者都可以让您将键设置为值,检索这些值,删除键并检测是否在键处存储了某些内容。因此(并且因为没有内置的替代方法),对象在历史上一直被用作地图。但是,在某些情况下,使用地图有一些重要的区别:
答案 5 :(得分:7)
es2015版本:
const myMap = new Map(objArray.map(obj => [ obj.key, obj.val ]));
答案 6 :(得分:6)
使用ES6扩展+ Object.assign:
eval.__file__,
os.path.abspath(eval.__file__)
inspect.getfile(eval).
答案 7 :(得分:4)
这是我在TypeScript中所做的,我有一个小utils库,我在其中放置了这样的内容
export const arrayToHash = (array: any[], id: string = 'id') =>
array.reduce((obj, item) => (obj[item[id]] = item , obj), {})
用法:
const hash = arrayToHash([{id:1,data:'data'},{id:2,data:'data'}])
或者如果您使用的标识符不是“ id”
const hash = arrayToHash([{key:1,data:'data'},{key:2,data:'data'}], 'key')
答案 8 :(得分:2)
使用简单的Javascript
var createMapFromList = function(objectList, property) {
var objMap = {};
objectList.forEach(function(obj) {
objMap[obj[property]] = obj;
});
return objMap;
};
// objectList - the array ; property - property as the key
答案 9 :(得分:1)
有更好的方法可以做到这一点,正如其他张贴者所解释的那样。但是,如果我想坚持使用纯JS和ol'的方式,那就是:
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);
答案 10 :(得分:1)
library(Morpho)
data(iris)
vari <- iris[,1:4]
facto <- iris[,5]
cva.1=CVA(vari, groups=facto)
用法上的小改进:
reduce
答案 11 :(得分:1)
如果要转换为新的ES6 Map,请执行以下操作:
var kvArray = [['key1', 'value1'], ['key2', 'value2']];
var myMap = new Map(kvArray);
为什么要使用这种类型的地图?好吧,这取决于您。看看this。
答案 12 :(得分:1)
尝试
let toHashMap = (a,f) => a.reduce((a,c)=> (a[f(c)]=c,a),{});
let arr=[
{id:123, name:'naveen'},
{id:345, name:"kumar"}
];
let fkey = o => o.id; // function changing object to string (key)
let toHashMap = (a,f) => a.reduce((a,c)=> (a[f(c)]=c,a),{});
console.log( toHashMap(arr,fkey) );
// Adding to prototype is NOT recommented:
//
// Array.prototype.toHashMap = function(f) { return toHashMap(this,f) };
// console.log( arr.toHashMap(fkey) );
答案 13 :(得分:1)
您可以使用新的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}
答案 14 :(得分:1)
使用 import Foundation
import CoreData
extension User {
@nonobjc public class func fetchRequest() -> NSFetchRequest<User> {
return NSFetchRequest<User>(entityName: "User")
}
@NSManaged public var id: Int32
@NSManaged public var name: String
@NSManaged public var username: String
@NSManaged public var email: String
@NSManaged public var address: Address
@NSManaged public var avatar: String
@NSManaged public var phone: String
@NSManaged public var website: String
@NSManaged public var company: Company
@NSManaged public var addressRe: Address
@NSManaged public var companyRe: Company
}
:
import Foundation
import CoreData
@objc(User)
public class User: NSManagedObject {
}
答案 15 :(得分:0)
以下是我在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;
};
您可以在此处找到要点:https://gist.github.com/naveen-ithappu/c7cd5026f6002131c1fa