Does JavaScript have a map function t...
Does JavaScript have a map function t...
No, JavaScript does not have a native map
function specifically designed to iterate directly over object properties like it does for arrays. However, there are several methods to achieve similar functionality by converting the object properties to an array format, which can then be iterated over using array methods such as map
.
To iterate over object properties and apply a function to each value, you can use the Object.keys()
method to extract an array of the object's keys and then use array methods to iterate over these keys and apply transformations. Here's an example:
const myObject = { a: 1, b: 2, c: 3 };
const newObject = Object.keys(myObject).reduce((acc, key) => {
acc[key] = myObject[key] * 2; // Applying a transformation function
return acc;
}, {});
console.log(newObject); // { a: 2, b: 4, c: 6 }
Alternatively, you can use the Object.entries()
method, which returns an array of key-value pairs, and then use the map()
function on this array to transform each entry. After transformations, you can convert it back to an object using Object.fromEntries()
:
...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào