I have the following array in Javascript with the following objects
let listado = [
{ a: 1, b: 3, c: 3, d: 4 },
{ a: 2, b: 13, c: 6, d: 9 },
{ a: 53, b: 12, c: 98, d: 27 }
];
What I want is for each element of the array to reduce the number of attributes to only a specific number, to say something that only the attributes a
and are left for the list of the example c
:
listado = [
{ a: 1, c: 3 },
{ a: 2, c: 6 },
{ a: 53, c: 98 }
];
Is there a javascript function that does this for me or do I have to go through the array element by element and eliminate the attributes?
"Reducing" the amount of attributes would be something permanent that would affect the original fix, this type of collateral effects can be harmful to another component. If you want to use the functional programming approach, the option is to use the
map
. What you should do is return a new object that has "the shape" you want.So what you are doing is creating a new array with new objects, leaving the original array intact, which is very useful if you then need to create another array but with a different shape.
If this were nodejs (instead of a browser) you could make it simpler with arrow functions.
Even using object destructuring you can simplify it
Note: it is mentioned that this works in browsers and it is correct but not in all, these features are specific to ECMAScript 2015 and there are many browsers that do not support these features, but they are still on the market. Depending on the minimal browser your development is targeting, you might consider using it or not.
I admit that I don't know of a native function that does it, but you can use this function that only leaves the properties that you specify in the second parameter:
There is a native function that does the work for you. It's called delete
Here an example with your objects you place:
And well, what I do is use . map to traverse the container array of objects and for each iteration I apply delete to the desired property.