1

I want to trim the occurrences of object key y_ and get output like useroutput:

var user =[{"data":"2","y_data1":1},{"data":"4","y_data1":3,"y_data2":3}]
var useroutput=[{"data":"2","data1":1},{"data":"4","data1":3,"data2":3}]

Let me know of any approaches using lodash or javascript.

Gautham Shetty
  • 361
  • 1
  • 5
  • 13

2 Answers2

2

You can use lodash#map to transform each item in the user array and lodash#mapKeys to transorm each of the user item's keys.

const result = _.map(user, data => 
  _.mapKeys(data, (v, k) => k.replace(/^y_/, '')));

const user = [
  {"data":"2","y_data1":1},
  {"data":"4","y_data1":3,"y_data2":3}
];

const result = _.map(user, data => 
  _.mapKeys(data, (v, k) => k.replace(/^y_/, '')));

console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Pure JS solution: Use Array#map for the item transformation, and a combination of Object.entries() and Array#reduce to achieve the key transformation.

const result = user.map(data =>
  Object.entries(data).reduce(
    (r, [k, v]) => (r[k.replace(/^y_/, '')] = v, r),
    {}
  )
);

const user = [
  {"data":"2","y_data1":1},
  {"data":"4","y_data1":3,"y_data2":3}
];

const result = user.map(data =>
  Object.entries(data).reduce(
    (r, [k, v]) => (r[k.replace(/^y_/, '')] = v, r),
    {}
  )
);

console.log(result);
.as-console-wrapper{min-height: 100%; top: 0}
ryeballar
  • 29,658
  • 10
  • 65
  • 74
1

You can do it without lodash using array.map, array.reduce and a regex to match your target key as follows:

var user = [{"data":"2","y_1":1},{"data":"4","y_1":3,"y_2":3}]; 

console.log(user.map(o => 
  Object.keys(o).reduce((a, e) => {
    a[e.replace(/^y_/, "")] = o[e];
    return a;
  },
{})));
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 1
    i used above method but I am seeing a discrepency in order here internally javscript is doing sorting when it end up in integer key var user = [{"data":"2","y_1":1},{"data":"4","y_1":3,"y_2":3}]; var useroutput = [{"1":1,"data":"2"},{"1":3,"2":3,"data":"4"}]; how we can avoid this – Gautham Shetty Aug 29 '18 at 07:13
  • I wouldn't count on object keys to be in [any particular order](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order). I'll look into a way to preserve it though. – ggorlen Aug 29 '18 at 22:01