phantomphoenix phantomphoenix - 3 months ago 12
Javascript Question

filter the object key and create new nested keys

I have an array of parameters like this:

[param1, param2_experience, param3]


I have another array of objects like this:

[
{
id: 123,
param1_issue: "some",
param1_star: 5,
param2_experience_time_taken: "45 minutes",
param3_issue_other: "some other"
},
{
id: 456,
param1_issue: "some issue",
param1_star: 3.5,
param3_issue_other: "some other issue"
}
]


I want to spilt this array basis on the first array. something like this:

[
{
id: 123,
param1: {
issue: "some",
star: 5
},
param2_experience: {
time_taken: "45 minutes"
},
param3: {
issue_other: "some other"
}
},
{
id: 456,
param1: {
issue: "some issue",
star: 3.5
},
param3: {
issue_other: "some other issue"
}
}
]


What would be a better way to do it? This array can contain thousands of objects.

Answer

You can map each element in the array to a new object that has the format from you first array.

var keys = ["param1", "param2_experience", "param3"];
var data = [{"id":123,"param1_issue":"some","param1_star":5,"param2_experience_time_taken":"45 minutes","param3_issue_other":"some other"},{"id":456,"param1_issue":"some issue","param1_star":3.5,"param3_issue_other":"some other issue"}];

var output = _.map(data, e => {
  var obj = {};
  _.forIn(e, (val, key) => {
    var bucket = _.find(keys, k => _.startsWith(key, k));
    _.set(obj,
          bucket 
            ? [bucket, key.slice(bucket.length + 1)]
            : key,
          val);
  });
  return obj;
});

console.log(output);
<script src="https://cdn.jsdelivr.net/lodash/4.14.1/lodash.min.js"></script>

Comments