【问题标题】:Split object into two and renumerate keys将对象拆分为两个并重新枚举键
【发布时间】:2022-01-15 05:49:43
【问题描述】:

我想根据属性“数量”(空字符串)将一个对象分成两部分

let myObj = {
"1": {
    "resources": "hotel",
    "amount": "",
    "currency": ""
},
"2": {
    "resources": null,
    "amount": "300.00",
    "currency": "CZK"
},
"3": {
    "resources": null,
    "amount": "500.00",
    "currency": "USD"
},

}

到这里

obj1 = {
"1": {
    "resources": "hotel",
    "amount": "",
    "currency": ""
}}
obj2 = {
"1": {
    "resources": null,
    "amount": "300.00",
    "currency": "CZK"
},
"2": {
    "resources": null,
    "amount": "500.00",
    "currency": "USD"
}}

我接近解决它,但经过多次尝试(推送、分配、映射)后仍然无法正常工作。谢谢。

【问题讨论】:

标签: javascript javascript-objects


【解决方案1】:

这是我想到的最简单且可读性最强的解决方案。

const obj = {
    "1": {
        "resources": "hotel",
        "amount": "",
        "currency": ""
    },
    "2": {
        "resources": null,
        "amount": "300.00",
        "currency": "CZK"
    },
    "3": {
        "resources": null,
        "amount": "500.00",
        "currency": "USD"
    }
}

const withAmount = {};
const withoutAmount = {};

for(indexKey in obj) {
  const data = obj[indexKey];
  if(data['amount'] != '') {
    withAmount[indexKey] = data;
  } else {
    withoutAmount[indexKey] = data;
  }
}

console.log({withAmount, withoutAmount});

【讨论】:

  • 似乎有效 - 非常感谢。
【解决方案2】:

你可以这样实现你的目标:

let myObj = {
  "1": {
    "resources": "hotel",
    "amount": "",
    "currency": ""
  },
  "2": {
    "resources": null,
    "amount": "300.00",
    "currency": "CZK"
  },
  "3": {
    "resources": null,
    "amount": "500.00",
    "currency": "USD"
  },
}

const withAmount = {},
  withoutAmount = {};

Object.keys(myObj).forEach(key => {
  const item = myObj[key];
  if (item.amount) {
    withAmount[key] = item;
  } else {
    withoutAmount[key] = item
  }
})

console.log('withAmount:',withAmount)
console.log('withoutAmount:',withoutAmount)

【讨论】:

  • 这是我的救赎(将键更改为 i++ 所以都以 1 开头)谢谢
猜你喜欢
  • 2018-10-30
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 2014-10-03
  • 2016-07-03
  • 1970-01-01
  • 2021-10-10
相关资源
最近更新 更多