There is no native map
to the Object
object, but how about this:
(没有到Object
对象的本地map
,但是如何处理:)
var myObject = { 'a': 1, 'b': 2, 'c': 3 }; Object.keys(myObject).map(function(key, index) { myObject[key] *= 2; }); console.log(myObject); // => { 'a': 2, 'b': 4, 'c': 6 }
But you could easily iterate over an object using for ... in
:
(但是您可以使用for ... in
以下对象中轻松迭代对象:)
var myObject = { 'a': 1, 'b': 2, 'c': 3 }; for (var key in myObject) { if (myObject.hasOwnProperty(key)) { myObject[key] *= 2; } } console.log(myObject); // { 'a': 2, 'b': 4, 'c': 6 }
Update
(更新资料)
A lot of people are mentioning that the previous methods do not return a new object, but rather operate on the object itself.
(很多人提到,以前的方法不会返回新对象,而是对对象本身进行操作。)
For that matter I wanted to add another solution that returns a new object and leaves the original object as it is: (为此,我想添加另一个解决方案,该解决方案返回一个新对象并保留原始对象不变:)
var myObject = { 'a': 1, 'b': 2, 'c': 3 }; // returns a new object with the values at each key mapped using mapFn(value) function objectMap(object, mapFn) { return Object.keys(object).reduce(function(result, key) { result[key] = mapFn(object[key]) return result }, {}) } var newObject = objectMap(myObject, function(value) { return value * 2 }) console.log(newObject); // => { 'a': 2, 'b': 4, 'c': 6 } console.log(myObject); // => { 'a': 1, 'b': 2, 'c': 3 }
Array.prototype.reduce
reduces an array to a single value by somewhat merging the previous value with the current.
(Array.prototype.reduce
通过将先前值与当前值进行某种程度的合并,将数组减少为单个值。)
The chain is initialized by an empty object {}
. (该链由一个空对象{}
初始化。)
On every iteration a new key of myObject
is added with twice the key as the value. (每次迭代时,都会添加myObject
的新键,并将键的值加倍。)
Update
(更新资料)
With new ES6 features, there is a more elegant way to express objectMap
.
(借助ES6的新功能,有一种更优雅的方式来表达objectMap
。)
const objectMap = (obj, fn) => Object.fromEntries( Object.entries(obj).map( ([k, v], i) => [k, fn(v, k, i)] ) ) const myObject = { a: 1, b: 2, c: 3 } console.log(objectMap(myObject, v => 2 * v))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…