我可以在上面使用更高的功能吗?

时间:2018-09-26 16:08:42

标签: javascript arrays function object for-loop

这是我想知道是否要在其他功能中使用的代码,例如ForEachmapfilterwhat else吗?
那可能吗?

const val = 'Mike,Mike@mail.com,male'

const split = val.split(',')
console.log(split) //to check

const newObj = {}

newObj.name = split[0]
newObj.email = split[1]
newObj.gender = split[2]

console.log(newObj)

const val2 = 'name:John,email:John@mail.com'

const split2 = val2.split(',')
 console.log(split2) //to check
const newObj2 = {}

  for(var i = 0; i < split2.length; i++) {
    var data = split2[i].split(':')
    newObj2[data[0]] = data[1]
  }

console.log(newObj2)

想要使代码更简洁明了

2 个答案:

答案 0 :(得分:1)

const val = 'Mike,Mike@mail.com,male'

const [name, email, gender] = val.split(',')

console.log({name, email, gender})

const val2 = 'name:John,email:John@mail.com'

const splitByColon = term => {
  const [key, value] = term.split(':')
  return {[key]: value}
}

console.log(
  val2
    .split(',')
    .reduce((acc, term) =>
      ({...acc, ...splitByColon(term)}), {})
)

答案 1 :(得分:0)

另一种方式可能是

const val = 'name:Mike,email:Mike@mail.com,gender:male'

const obj = {}
val.split(',')
   .map(prop => prop.split(':'))
   .forEach(([key, value]) => {
     obj[key] = value
   })

console.log(obj)