I have a users object where I am trying to create different object called element using the values of Users object. My code looks like below. I want to know that can this code be written in more efficient manner as I want to remove null object from the output.
var users = {
"accounts": [{
"accountId": "210001"
},
{
"accountId": "90000",
"accountText": "Sample"
},
{
"accountId": "4618891",
"accountText": "Test"
}
]
};
var obj = {};
var element = {},
cart = [];
users["accounts"].forEach(user => {
obj = {
...obj,
"M": {
"accountId": {
"S": user.accountId
},
"accountText": {
"S": user.accountText
}
}
}
cart.push(obj);
})
element["L"] = cart;
console.log(JSON.stringify(element))
Expected Output
{
"L": [{
"M": {
"accountId": {
"S": "210001"
}
}
},
{
"M": {
"accountId": {
"S": "90000"
},
"accountText": {
"S": "Sample"
}
}
},
{
"M": {
"accountId": {
"S": "4618891"
},
"accountText": {
"S": "Test"
}
}
}
]
}
Not smaller but more readable
var users = {
"accounts": [{
"accountId": "210001"
},
{
"accountId": "90000",
"accountText": "Sample"
},
{
"accountId": "4618891",
"accountText": "Test"
}
]
};
var obj = {};
var element = {},
cart = [];
users["accounts"].forEach(user => {
obj = { ...obj, "M": { } };
if (user.accountText) obj.M.accountText = { "S": user.accountText}
if (user.accountId) obj.M.accountId = { "S": user.accountId }
cart.push(obj);
})
element["L"] = cart;
console.log(element)
Reduce with delete
var users = {
"accounts": [{
"accountId": "210001"
},
{
"accountId": "90000",
"accountText": "Sample"
},
{
"accountId": "4618891",
"accountText": "Test"
}
]
};
const element = {},
cart = users["accounts"].reduce((acc,user) => {
const obj = {
"M": {
accountText: { "S": user.accountText},
accountId : { "S": user.accountId }
}
}
if (!user.accountText) delete obj.M.accountText
if (!user.accountId) delete obj.M.accountId
acc.push(obj);
return acc
},[])
element["L"] = cart;
console.log(element)
Perhaps a shorter code with dynamic keys?
const users = {
accounts: [{
accountId: '210001'
},
{
accountId: '90000',
accountText: 'Sample'
},
{
accountId: '4618891',
accountText: 'Test'
},
{
accountId: '46188911',
accountText: null
}
]
}
const aa = users.accounts.map(x => {
return {
M: Object.entries(x)
.reduce((acc, curr) => {
return curr[1] // check for null values
? { ...acc, [curr[0]]: { S: curr[1] } }
: acc
}, {})
}
})
const elements = { L: aa }
console.log(JSON.stringify(elements, null, 2))
For dynamic inner and outer key:
const users = {
accounts: [{
accountId: '210001'
},
{
accountId: '90000',
accountText: 'Sample'
},
{
accountId: '4618891',
accountText: 'Test'
},
{
accountId: '46188911',
accountText: null
}
]
}
const outerKey = 'MM'
const innerKey = 'SS'
const aa = users.accounts.map(x => {
return {
[outerKey]: Object.entries(x)
.reduce((acc, curr) => {
return curr[1] // check for null values
? { ...acc, [curr[0]]: { [innerKey]: curr[1] } }
: acc
}, {})
}
})
const elements = { L: aa }
console.log(JSON.stringify(elements, null, 2))