将对象拆分为两个并重新枚举键

Split object into two and renumerate keys

我想根据属性“金额”(空字符串)

将一个对象分成两部分
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"
}}

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

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

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});

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

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)