Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to loop trough an objects and dynamically push items to array in javasript

I am a python dev for the most part and im trying to solve a quick problem using javasript. I have the following data:


data = {
  name: "james_0",
  hobby: "dev_0",
  country: "usa",
}

i want to make sure each item included in the objects data which values ends with "_0" is push to an objects, then all those fields get pushed to an array

expected results

data = [{name: "james_0", hobby: "dev_0"}]

I tried the following codes but seem to be missing something

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


const result = []

for (const [key, value] of Object.entries(data)) {
  if (value.endsWith("_0")) {

    result.push({key: value}) <== Something seem to be missing around this
  }
  
}

console.log("result", result)

>Solution :

const data = {
  name: "james_0",
  hobby: "dev_0",
  country: "usa",
}


function deleteNonIncluding (data = {}){
  const values = Object.values(data).filter(el => el.includes("_0"))
  
  const objectValues = Object.keys(data);
  
  
    const newObject = values.reduce((accumulator, value, index) => {
  return {...accumulator, [objectValues[index]]: value};
}, {});
  
  return [newObject]
}

const newArray = deleteNonIncluding(data);

console.log(newArray)

Is this what you needed? It was kinda confusing following your question.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading