javascript extract certain properties from all objects in array
Solution 1:
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);
Solution 2:
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)
Solution 3:
map creates a new array, so there is no need to delete any thing, instead create an array of interesting keys and return it
var dummyArray = [{
"att1": "something",
"att2": "something",
"att20": "something",
"att100": "something"
}, {
"att1": "something",
"att2": "something",
"att20": "something",
"att100": "something"
}];
let x = dummyArray.map((item) => {
return {
attr20: item.att20
}
})
console.log(x)