I would like to split an object into two parts according to property “amount” (empty string)
JavaScript
x
17
17
1
let myObj = {
2
"1": {
3
"resources": "hotel",
4
"amount": "",
5
"currency": ""
6
},
7
"2": {
8
"resources": null,
9
"amount": "300.00",
10
"currency": "CZK"
11
},
12
"3": {
13
"resources": null,
14
"amount": "500.00",
15
"currency": "USD"
16
},
17
}
to this
JavaScript
1
18
18
1
obj1 = {
2
"1": {
3
"resources": "hotel",
4
"amount": "",
5
"currency": ""
6
}}
7
obj2 = {
8
"1": {
9
"resources": null,
10
"amount": "300.00",
11
"currency": "CZK"
12
},
13
"2": {
14
"resources": null,
15
"amount": "500.00",
16
"currency": "USD"
17
}}
18
I’m close to solving it but after numerous attempts (push, assign, map) it still does not work. Thx.
Advertisement
Answer
You can acheive your goal like this:
JavaScript
1
32
32
1
let myObj = {
2
"1": {
3
"resources": "hotel",
4
"amount": "",
5
"currency": ""
6
},
7
"2": {
8
"resources": null,
9
"amount": "300.00",
10
"currency": "CZK"
11
},
12
"3": {
13
"resources": null,
14
"amount": "500.00",
15
"currency": "USD"
16
},
17
}
18
19
const withAmount = {},
20
withoutAmount = {};
21
22
Object.keys(myObj).forEach(key => {
23
const item = myObj[key];
24
if (item.amount) {
25
withAmount[key] = item;
26
} else {
27
withoutAmount[key] = item
28
}
29
})
30
31
console.log('withAmount:',withAmount)
32
console.log('withoutAmount:',withoutAmount)