The map function of the implementation object is similar to array prototype. map

Time:2022-5-8
//Implement a map function
const targetData = {
  a:2,
  b:3,
  c:4
}
const objMap = (obj,fn)=>{
  if(typeof fn !=="function"){
    throw new TypeError(`${fn} is not a function !`);
  }
  return JSON.parse(JSON.stringify(obj,fn));
}
const tempArr =  objMap(targetData,(key,value)=>{
  if(value%2===0){
    return value/2
  }
  return value
})
console.log(tempArr)//{a: 1, b: 3, c: 2, d: 5}

JSON.stringify()

JSON. Stringify (value, replace, space), which is used to convert JavaScript values into JSON strings. (the above cases are two parameters)

  • Value: required. The JavaScript value to be converted is usually an object or array
  • Replace: optional, function or array used to convert the result. If it is a function, JSON Stringify will call this function and pass in the key and value of each member, using the return value instead of the original value. If this function returns undefined, the member will be photographed, and the key of the root object is an empty string: ”. If the replacement is an array, only the members with key values in the array are converted. The conversion order of members is the same as that in the array.
  • Space: optional. Indent, space and line feed are added to the text. If space is a number, the return value text is indented by a specified number of spaces at each level. If space is greater than 10, the text is indented by 10 spaces.