I have an array of objects with the same properties. Each object has around a hundred properties. I want to keep only a handful of them in a new array:
var dummyArray = [{ "att1": "something", "att2": "something", ..., "att100": "something"}, { "att1": "something", "att2": "something", ..., "att100": "something"}, ...];
How can I filter/map/reduce... and extract the interesting keys?
const newDummArray = dummyArray.map(function(item) {
delete item.att1;
delete item.att3;
delete item.att15;
// ... (long list)
return item;
});
how can I keep only att20
, att30
, att70
, att80
for each object and delete the rest?
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
store the props you want to keep in an array then for each object transfer wanted props to a new object.
var dummyArray = [{ "att1": "something", "att2": "something", "att100": "something"}, { "att1": "something", "att2": "something", "att100": "something"}];
var propsToKeep = ["att1", "att100"];
var result = dummyArray.map(item => {
const obj = {};
for (const prop of propsToKeep) {
obj[prop] = item[prop];
}
return obj;
})
console.log(result)
Use object destructuring to get the properties, and generate a new object using shorthand property names:
const dummyArray = [{ "att20": "att20", "att30": "att30", "att70": "att70", "att80": "att80"}, { "att20": "att20", "att30": "att30", "att70": "att70", "att80": "att80"}];
const result = dummyArray.map(({ att20, att30, att70, att80 }) => ({
att20,
att30,
att70,
att80
}));
console.log(result);
I have find easiest way to do this JSON.stringify()
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
const odata = [
{ "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55 },
{ "id": "0002", "type": "ansd", "name": "EARK", "ppu": 0.67 }
];
const outdata=JSON.stringify(odata,['id','type']);
console.log(outdata);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With