NodeJS 如何唯一数组对象值?

fykwrbwg  于 2022-11-22  发布在  Node.js
关注(0)|答案(1)|浏览(174)

下面你可以看到我的NodeJS代码,在这里我想打印的对象的值,唯一的名称。

Array.prototype.uniqueArray = function (...props) {

  if (!props || (props instanceof Array && props.length === 0)) {
    return [...this]
  } else if (props instanceof Array===true) {
    return 'Invalid Parameter Type'
  }else{
    console.log("test 123")
  }
}

console.log([ ].uniqueArray('name') )
console.log([ {id: 1, name: "Jony"}, {id: 2, name: "Jony"}, {id: 3, name: "Kane"}].uniqueArray('name') )
console.log([ {id: 1, name: "Jony"}, {id: 2, name: "Jony"}, {id: 3, name: "Kane"}].uniqueArray('test') )

我想打印,如果我们输入空数组,返回相同的空数组(如[]),如果我们传递参数,如'name',它将根据'name'返回唯一的数据。所以我可以得到这些输出正确。
但是作为第三个'console.log'部分,当我们传递不包含在数组对象(如'test')中的无效参数时,我希望返回“Invalid Parameter Type”。对于第三个'console.log'部分,我可以得到以下结果:
输出量:

[ { id: 1, name: 'Jony'} ]

预期输出:

'Invalid Parameter Type'
fkvaft9z

fkvaft9z1#

一种方法可能是将对象删除到一个新的数组中,如果该数组为空,您将知道是否在任何对象中都没有找到该参数。

// Double check that uniqueArray doesn't exist
// on the array prototype
if (!('uniqueArray' in Array.prototype)) {
  
  // You're only sending in one argument to the
  // function so there's no need to spread it.
  Array.prototype.uniqueArray = function(prop) {
    
    // If there is no prop or or there is but it's not
    // a string, or the array is empty, return the array
    if ((!prop || typeof prop !== 'string') || !this.length) {
      return this;
    }

    // Iterate over the array of objects with reduce,
    // initialising it with a Map. This will hold our deduped
    // objects.
    const deduped = this.reduce((acc, obj) => {
      
      // Using the prop argument find the key which is
      // the value of that property in the object.
      const key = obj[prop];
      
      // If that key doesn't exist on the Map add it,
      // and set its value as the object
      if (key && !acc.has(key)) acc.set(key, obj);
      
      // Return the Map for the next iteration
      return acc;

    }, new Map());
    
    // Grab the values from the Map, and coerce them back
    // to an array
    const arr = [...deduped.values()];

    // If there are no objects in the array it means there were
    // no objects with values that matched the argument, so
    // return a message
    if (!arr.length) return 'Invalid Parameter Type';
    
    // Otherwise return the array
    return arr;
  
  }

}

console.log([ ].uniqueArray('name'));
console.log([ ].uniqueArray(23));
console.log([ {id: 1, name: "Jony"}, {id: 2, name: "Jony"}, {id: 3, name: "Kane"}].uniqueArray('name'));
console.log([ {id: 1, name: "Jony"}, {id: 2, name: "Jony"}, {id: 3, name: "Kane"}].uniqueArray('test'));

相关问题