-1

I am using reactjs have the following data below and I want to loop through the array then if key === "oneline" or key === "twoline" remove the entire object.

In this example after removing the two objects (transformation), based on the description above it will only return objects with 0 and 3 inside the array.

const data = [
   {0: {key: "zeroline", door: "zero"}},
   {1: {key: "oneline", door: "one"}},
   {2: {key: "twoline", door: "two"}},
   {3: {key: "threeline", door: "three"}},
]

Any help would be very helpful.

1

3 Answers 3

1

Use Array filter method. The filter() method creates an array filled with all array elements that pass a test. The syntax of Array filter: array.filter(function(currentValue, index, arr), thisValue)

const data = [
  { 0: { key: "zeroline", door: "zero" } },
  { 1: { key: "oneline", door: "one" } },
  { 2: { key: "twoline", door: "two" } },
  { 3: { key: "threeline", door: "three" } },
];

let ret = data.filter((x, i) => x[i].key !== "oneline" && x[i].key !== "twoline");
console.log(ret);

Sign up to request clarification or add additional context in comments.

Comments

1

You could filter it out with Array#filter.

const keywords = ['twoline', 'oneline'], data = [{0: {key: "zeroline", door: "zero"}},{1: {key: "oneline", door: "one"}},{2: {key: "twoline", door: "two"}},{3: {key: "threeline", door: "three"}}];

const res = data.filter((v, i) => keywords.indexOf(v[i].key) === -1);

console.log(res);

Comments

1

One way of doing it is:

const result = Object.keys(data).reduce((filtered,key,index) => {
   //Getting specific object of array
   //Example for first: data[0]["0"] === {key: "zeroline",door "zero"}
   const object = data[index][key];
   
   //Check if object key is zeroline or twoline
   if(object.key === "zeroline" || object.key === "twoline"){
     //If it is we push object to array
     filtered.push(object)
    }
   return filtered
},[])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.