javascript 我怎么能改变标签的过滤对象

ffx8fchx  于 2023-05-12  发布在  Java
关注(0)|答案(1)|浏览(96)

我试图从对象数组中过滤数据,这做得很好,但我想改变标签,我怎么能做到这一点,这是我的代码看起来很像

let items = this.mydata;
          let aSelectedData = [];
          const aAcceptedKeys = ["billingAcc", "System"];
          aSelectedData = items.map(function (v, k) {
          let nestedObjects = [];
            for (let i = 0; i < aAcceptedKeys.length; i++) {
            let k = i;
            let v1 = aAcceptedKeys[k];
              if (typeof v[v1] != 'undefined') {
                nestedObjects[v1] = v[v1];
              }
            }
            return Object.assign({}, nestedObjects);
          });

我希望标签是:billinvoice,而不是billingAccSystem
代码添加到上面我已经尝试到现在

njthzxwz

njthzxwz1#

如果你的数据是经过清理的(所有项都是对象,它们都有billingAccSystem),最短的语法是:

const prettyData = myData.map(({ billingAcc: bill, System: invoice }) => ({
  bill,
  invoice
}))

测试:

const myData = Array.from({ length: 10 }).map((_, key) => ({
  billingAcc: `Bill ${key + 1}`,
  System: `Invoice ${key + 101}`
}))

const prettyData = myData.map(({ billingAcc: bill, System: invoice }) => ({
  bill,
  invoice
}))

console.log(prettyData)

如果你想过滤既没有billingAcc也没有System的项目,并且你不想在原始数据中不存在的结果项目中将billinvoice设置为undefined,这将起作用:

const isDefined = (item) => item !== undefined
const prettyData = myData
  .filter(({ billingAcc, System }) => [billingAcc, System].some(isDefined))
  .map(({ billingAcc: bill, System: invoice }) =>
    Object.assign(
      {},
      isDefined(bill) ? { bill } : {},
      isDefined(invoice) ? { invoice } : {}
    )
  )

测试:

const myData = [
  { billingAcc: '1', System: 'foo' },
  { billingAcc: '2', System: 'bar' },
  { foo: 'Skipped, no billingAcc or System' },
  { billingAcc: '' },
  { System: null },
  { billingAcc: 0 },
  { System: NaN },
  { billingAcc: void 0 } // void 0 === undefined, should be skipped
]
const isDefined = (item) => item !== undefined
const prettyData = myData
  .filter(({ billingAcc, System }) => [billingAcc, System].some(isDefined))
  .map(({ billingAcc: bill, System: invoice }) =>
    Object.assign(
      {},
      isDefined(bill) ? { bill } : {},
      isDefined(invoice) ? { invoice } : {}
    )
  )

console.log(prettyData)

相关问题