NodeJS 减少过滤JS对象的函数

ogq8wdun  于 2023-04-20  发布在  Node.js
关注(0)|答案(2)|浏览(119)

我有一个这样的JS对象:

{"field1":1,"field3":14,"category":9,"completion":null,"creation":"23-04-26", "settings":"[{"ip":""}]"}

我想创建一个函数,它返回这样的对象没有字段,这是string-array**“settings”:“[{“ip”:“"}]"**,如果这个数组只包含一个元素,如果这个对象只包含一个键值对,值为空字符串。
预期结果为:

{"field1":1,"field3":14,"category":9,"completion":null,"creation":"23-04-26"}

不筛选的数组:

{"field1":1,"field3":14,"category":9,"completion":null,"creation":"23-04-26", "settings":"[{"ip":"33333not empty"}]"}

或:

{"field1":1,"field3":14,"category":9,"completion":null,"creation":"23-04-26", "settings":"[{"ip":"345", "dns": "address"}]"}

我写了如下函数:

function filterArrayFields(values) {
  const result = {};

  const fieldNames = Object.keys(values);

  fieldNames.forEach((fieldName) => {
    if (typeof values[fieldName] !== 'string') {
      result[fieldName] = values[fieldName];
      return;
    }

    try {
      const parsedValue = JSON.parse(values[fieldName]);

      if (!Array.isArray(parsedValue)) {
        result[fieldName] = values[fieldName];
        return;
      }

      if (Array.isArray(parsedValue) && parsedValue.length > 1) {
        result[fieldName] = values[fieldName];
        return;
      }

      if (Array.isArray(parsedValue) && parsedValue.length === 1) {
        const arrayTypeFieldValue = parsedValue[0];

        const [arrayTypeFieldValueName] = Object.keys(arrayTypeFieldValue);

        if (arrayTypeFieldValue[arrayTypeFieldValueName] !== '') {
          result[fieldName] = values[fieldName];
          return;
        }
      }
    } catch (error) {
      result[fieldName] = values[fieldName];
    }
  });

  return result;
}

这个方法工作正常,但看起来像是重载了buyif-s或额外的条件。有没有可能优化这个函数?

aiqt4smr

aiqt4smr1#

我认为,您可以通过spread操作符浅克隆输入对象,并仅在它符合您的标准时才有条件地将设置合并回来,从而显著地加强这一点。
标准测试可以由单独的专用函数处理。类似于以下内容:

function stripEmptySettings (obj) {
  const { settings, ...rest } = obj;
  return {
    ...rest,
    ...stripSettings(JSON.parse(settings)),
  }
}

function stripSettings (settings) {
  if (
    settings?.length === 1
    && Object.keys(settings[0]).length === 1
    && Object.values(settings[0]).every(v => v === '')
  ) {
    return;
  }
  return {settings};
}

const inputs = [
  {"field1":1,"field3":14,"category":9,"completion":null,"creation":"23-04-26", "settings":"[{\"ip\":\"\"}]"},
  {"field1":1,"field3":14,"category":9,"completion":null,"creation":"23-04-26", "settings":"[{\"ip\":\"33333not empty\"}]"},
  {"field1":1,"field3":14,"category":9,"completion":null,"creation":"23-04-26", "settings":"[{\"ip\":\"345\", \"dns\": \"address\"}]"}
]

const results = inputs.map(stripEmptySettings);

console.log(JSON.stringify(results, null, 3));
mwngjboj

mwngjboj2#

JS有一个内置的过滤器函数。对于设置值使用JSON.stringify()JSON.parse()将是最简单的方法来序列化数组

const filteredList = fieldNames.filter(field => {
  if("settings" in field){
    let settings = JSON.parse(field.settings)
    if(
      settings.length > 0 &&
      settings[0]
      ){
        let nonEmpty = false
        const keys = Object.keys(settings[0])
        for(let i =0; i < keys.length; i ++){
          if(settings[0][keys[i]]){
            nonEmpty = true
            break
          }
        }
        return nonEmpty
    }
    return false
  }
  return true
})

相关问题