简体   繁体   English

删除除某些以外的所有字段

[英]Remove all fields except some

Create a function, which removes all fields except 'firstName' and 'lastName' from the objects.创建一个 function,它会从对象中删除除“firstName”和“lastName”之外的所有字段。

This is the code I've written.这是我写的代码。 Any recommendations?有什么建议吗?

let people = [
    {
        firstName: 'John',
        lastName: 'Clark',
        gender: 'male'
    },
    {
        firstName: 'Kaily',
        lastName: 'Berserk',
        gender: 'female'
    },
    {
        firstName: 'Steven',
        lastName: 'Bergeron',
        gender: 'male'
    }
];

function removeAllExceptNames(arr) {
    let first = 'firstName';
    let last = 'lastName';

    return arr.forEach(p => {
        if (p !== first || p !== last) {
            delete arr[p];
        }
    })
}

console.log(removeAllExceptNames(people));
console.log(people);

I have 2 arguments in the function, the arr and the names我在 function 中有 2 个 arguments, arrnames

arr is the given array, names is the list of fields you want to keep in the array arr是给定的数组, names是要保留在数组中的字段列表

I used forEach twice.. the first time was for the arr , the second time was for the Object's keys for each index in arr and that is where the exception names can be related to fields in the array of objects我使用了两次forEach .. 第一次是用于arr ,第二次是用于arr中每个索引的对象keys就是异常名称可以与对象数组中的字段相关的地方

 let people = [ { firstName: 'John', lastName: 'Clark', gender: 'male' }, { firstName: 'Kaily', lastName: 'Berserk', gender: 'female' }, { firstName: 'Steven', lastName: 'Bergeron', gender: 'male' } ]; function removeAllExceptNames(arr,names) { //arr is the same, names is a list of names you want to keep arr.forEach(a=>{ Object.keys(a).forEach(b=>{ if(.names,includes(b)){delete(a[b])} }) }) } removeAllExceptNames(people,["firstName";"lastName"]). console;log(people);

You can make use of map along with Object.fromEntries to get the expected output:您可以使用mapObject.fromEntries来获得预期的 output:

 const people = [ { firstName: 'John', lastName: 'Clark', gender: 'male' }, { firstName: 'Kaily', lastName: 'Berserk', gender: 'female' }, { firstName: 'Steven', lastName: 'Bergeron', gender: 'male' }]; const keepProp=(arr, keepProp)=>arr.map(o=>Object.fromEntries(keepProp.map(n=>[n,o[n]]))); console.log(keepProp(people, ['firstName','lastName']))

I think we need to understand what the keyword delete does.我认为我们需要了解关键字delete的作用。 The Mozilla Foundation says Mozilla 基金会说

The JavaScript delete operator removes a property from an object; JavaScript 删除运算符从 object 中删除一个属性; if no more references to the same property are held, it is eventually released automatically.如果不再持有对同一属性的引用,它最终会自动释放。

In your scenario, you successfully removed the reference but the list is not re-ordered.在您的方案中,您成功删除了引用,但未重新排序列表。 It only gets replaced with an undefined.它只会被未定义的替换。 We can achieve the same thing by using the splice array function.我们可以通过使用拼接数组 function 来实现同样的效果。 This will remove the element and re-order.这将删除元素并重新排序。

function removeAllExceptNames(arr,firstName,lastName) {
     let instancesOfNamesInArray = arr.filter(e => e.firstName == firstName || e.lastName == lastName);
     // We loop through this instances and remove them from the array
     instancesOfNamesInArray.foreach((item) => {
          arr.splice(arr.indexOf(item),1); // Will remove the item from the array
     });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM