Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
Remove null object and can be written in more efficient way

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.

JSFIDDLE

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"
                }
            }
        }
    ]
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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)

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda