1

I'm trying to filter everything inside 'items' with 'name': "", without losing structure and values of fieldLabel and placeholder. Below is my current object:

result: {
    "fieldLabel": "foo",
    "placeholder": "foo",
    "items": [
        {
            "name": "foobar"
        },
        
            "name": ""
        },
        {
            "name": ""
        }
    ]
}

I want the object to look like this after filtering:

result: {
   "fieldLabel": "foo",
   "placeholder": "foo",
   ​"items": [
       ​{
           ​"name": "foobar"
       ​},       ​       ​       ​
   ​]
}

3 Answers 3

1
  1. Have a reference to the original object first.
const results = {
    "fieldLabel": "foo",
    "placeholder": "foo",
    "items": [
        {
            "name": "foobar"
        },
        {
            "name": ""
        },
        {
            "name": ""
        }
    ]
}
  1. Create a new object from the reference. Use spread syntax for copying object. Then filter method for filtering
const newObject = {
  ...results,
  items: results.items.filter(item => item.name)
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I was looking for. Thank you!!
1

You can filter the nested items array that have truthy name properties.

const result= {
  "fieldLabel": "foo",
  "placeholder": "foo",
  "items": [
    {
      "name": "foobar"
    },
    {
      "name": ""
    },
    {
      "name": ""
    }
  ]
};

result.items = result.items.filter(({ name }) => name);

console.log(result);

If you need to do this using an immutable pattern then shallow copy the object and nested properties that you are updating.

const result= {
  "fieldLabel": "foo",
  "placeholder": "foo",
  "items": [
    {
      "name": "foobar"
    },
    {
      "name": ""
    },
    {
      "name": ""
    }
  ]
};

const newresult = {
  ...result,
  items: result.items.filter(({ name }) => name)
};

console.log(newresult);
console.log(result === newresult); // false since new object

1 Comment

Thanks, using the spread syntax was a great solution.
0

Something like this?

Filter YOUROBJ.items to keep all entries where property name has a value that is not null/undefined/false

res.items = res.items.filter(e => e.name);

const obj = {
    "fieldLabel": "foo",
    "placeholder": "foo",
    "items": [
        {
            "name": "foobar"
        },
        {
            "name": ""
        },
        {
            "name": ""
        }
    ]
}

const res = Object.assign({}, obj); // copy object to not mutate the original one
res.items = res.items.filter(e => e.name); // filter array "items" to just keep items with property name
console.log(res);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.