I want to create a new array of objects without the gender field. Where is the mistake?
let collections = [
{ name: "Tom", gender: "male", age: 12 },
{ name: "Becky", gender: "female", age: 11 },
{ name: "Huck", gender: "male", age: 13 }
];
let newCollections = collections.slice();
let operations = {
select: function () {
let args = [].slice.call(arguments);
for (let i = 0; i < newCollections.length; i ) {
for (let key in newCollections[i]) {
for (let j = 0; j < args.length; j ) {
if (key !== args[j]) {
delete key;
return newCollections;
} } } } } };
const result = operations.select("name", "age");// the list of fields to save
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You could create an omit()
function that will return an object without a given property.
We can then use Array.map()
to run each item in the array through this:
let collections = [ { name: "Tom", gender: "male", age: 12 }, { name: "Becky", gender: "female", age: 11 }, { name: "Huck", gender: "male", age: 13 } ];
function omit(obj, field) {
return (({ [field]: _, ...result }) => result)(obj);
}
let newCollections = collections.map(person => omit(person, 'gender'));
console.log('New collections:', newCollections);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can do it using map method:
const array_without_gender = collections.map(el => {
return {name: el.name, age: el.age};
})
This code will create new array filled by objects without gender key,