数组转换嵌套对象

时间:2016-12-23 11:45:40

标签: javascript arrays object lodash

我想转换以下数组:

 let errors = [
   {
     field: "data.time",
     message: "less length than allowed"
   },
   {
     field: "data.time",
     message: "wrong format"
   },
   {
     field: "data.age",
     message: "too young"
   },
   { 
     field: "data.age",
     message: "not enough information"
   }
];

分为:

[
  { time: "less_length_than_allowed <br> wrong_format"},
  { age: "too_young <br> not_enough_information"},
]

我基本上想要删除字符串&#34;数据。&#34;对于每个字段属性。然后合并数组,将common字段作为对象键,并将值的消息串联起来。

这是我到目前为止所做的:

var removedData = errors.map(item => {
   item.field = item.field.slice(5);
   return item
});

var computedErrors = _.chain(removedData).groupBy('field').value();

5 个答案:

答案 0 :(得分:1)

您可以在普通js中使用reduce()来返回以下结果。

&#13;
&#13;
let errors = [{
  field: "data.time",
  message: "less length than allowed"
}, {
  field: "data.time",
  message: "wrong format"
}, {
  field: "data.age",
  message: "too young"
}, {
  field: "data.age",
  message: "not enough information"
}];

var o = {}
var result = errors.reduce(function(r, e) {
  var key = e.field.split('.')[1];
  var message = e.message.replace(/\s/g, '_');

  if (!o[key]) {
    o[key] = {[key]: message}
    r.push(o[key])
  } else {
    o[key][key] += ' <br> ' + message
  }
  return r;
}, [])

console.log(result)
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以这样做:

var age = [];
var time = [];
var removedData = errors.forEach(element => {
 if(element.field.contains('time')){ time.push(element.message); }
 if(element.field.contains('age')){ age.push(element.message); }
});

var removedData = {
 age: age.join('<br>'),
 time: time.join('<br>'),
}; 

答案 2 :(得分:0)

Data.Map.Strict

答案 3 :(得分:0)

_.chain(errors)
    .groupBy('field') // group errors by field
    .mapValues(function(items, key) { // iterate grouped arrays
        return _.chain(items)
            .map('message') // get message value from each item
            .join('<br>') // join messages
            .thru(function(str) {
                return _.set({}, key.replace(/data./g, ''), str); // transform to object
            })
            .value();
    })
    .values() // get object values
    .value();

答案 4 :(得分:0)

const errors = [{"field":"data.time","message":"less length than allowed"},{"field":"data.time","message":"wrong format"},{"field":"data.age","message":"too young"},{"field":"data.age","message":"not enough information"}];

const result = _(errors)
  .groupBy(({ field }) => field.split('.')[1])
  .mapValues((group) => 
    group.map(({ message }) => _.snakeCase(message))
    .join(' <br> ')
  )
  .map((value, key) => ({ [key]: value }))
  .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.3/lodash.min.js"></script>