Home > Software engineering >  how to loop trough an objects and dynamically push items to array in javasript
how to loop trough an objects and dynamically push items to array in javasript

Time:08-29

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


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)

CodePudding user response:

  1. Create an array of entries via Object.entries()
  2. Filter the values by their suffix
  3. Re-create an object using Object.fromEntries()
  4. Wrap the result in an array for some reason

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

const result = [
  Object.fromEntries(
    Object.entries(data).filter(([_, value]) => value.endsWith("_0"))
  ),
];

console.log(result);

CodePudding user response:

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.

  • Related