简体   繁体   中英

ES6 How to convert key, value pair to string recursively in javascript?

I try to interpolate error messages, because I need it in a special text format. Whats the best practice doing that nowadays :) thanks for any help!

http://codepen.io/radosch/pen/wWYPYG?editors=1111

desired outcome:

Password longer then 5 chars \n
Email has invalid format \n

Source:

let data = {
  "errors": [
    {
      "password": "must min have 5 characters"
    },
    {
      "email": "has invalid format"
    }
  ]
}

possible solution:

let res = data.errors.map(function(error, index) {
  let keyName = Object.keys(error)
  let str = error[keyName]
  return keyName + " " + str ;
});

console.log(res.join("\n"));

像这样吗

data.errors.map(error => Object.keys(error).map(key => `${key} ${error[key]}`)).join('\n');

Be aware that ES6 functions are very slow (at least on nodejs) ( but not only ), so I would still use ES5 functions, like

var res = '';
for (let i = 0; i < data.errors.length; i++) {
  var key = Object.keys(data.errors[i])[0];
  res += key + ' ' + data.errors[i][key] + '/n';
}

Benchmark:

question x 189,765 ops/sec ±1.39% (82 runs sampled)
maxx answer x 267,565 ops/sec ±0.98% (80 runs sampled)
for keys x 1,735,444 ops/sec ±0.85% (82 runs sampled)
Fastest is for keys

The test:

"use strict";
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;

suite
.add('map', function() {
let data = {
  "errors": [
    {
      "password": "must min have 5 characters"
    },
    {
      "email": "has invalid format"
    }
  ]
}

let res = data.errors.map(function(error, index) {
  let keyName = Object.keys(error)
  let str = error[keyName]
  return keyName + " " + str ;
});
res = res.join("\n");
})
.add('maxx answer', function() {
let data = {
  "errors": [
    {
      "password": "must min have 5 characters"
    },
    {
      "email": "has invalid format"
    }
  ]
}
data.errors.map(error => Object.keys(error).map(key => `${key} ${error[key]}`)).join('\n');

})
.add('for keys', function() {
let data = {
  "errors": [
    {
      "password": "must min have 5 characters"
    },
    {
      "email": "has invalid format"
    }
  ]
}

var res = '';
for (let i = 0; i < data.errors.length; i++) {
  var key = Object.keys(data.errors[i])[0];
  res += key + ' ' + data.errors[i][key] + '/n';
}
})
// add listeners
.on('cycle', function(event) {
  console.log(String(event.target));
})
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM