0

I have an arrays with ids and object lists with same ids contained in arrays, how can I remove objects based from array ids?

array:

user_ids: [“id001”, “id004”]

object list:

{
    {
        “user_id”: “id001”,
        “city”: “Seattle”
    },
    {
        “user_id”: “id002”,
        “city”: “Los Angeles”
    },
    {
        “user_id”: “id003”,
        “city”: “San Francisco”
    },
    {
        “user_id”: “id004”,
        “city”: “San Diego”
    }
}

so the result would be:

{
    {
        “user_id”: “id002”,
        “city”: “Los Angeles”
    },
    {
        “user_id”: “id003”,
        “city”: “San Francisco”
    }
}
2
  • Is that object an array of objects? Commented Nov 16, 2018 at 0:10
  • Your example is not syntactically valid. Commented Nov 16, 2018 at 0:33

2 Answers 2

1

Array methods

Array.prototype.filter()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Array.prototype.includes()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

let user_ids = ["id001", "id004"];
let list = [
    {
        "user_id": "id001",
        "city": "Seattle"
    },
    {
        "user_id": "id002",
        "city": "Los Angeles"
    },
    {
        "user_id": "id003",
        "city": "San Francisco"
    },
    {
        "user_id": "id004",
        "city": "San Diego"
    }
];

console.log(list.filter( o => !(user_ids.includes(o.user_id)) ));

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

Comments

0

If the list of objects is an array, you could do it like so:

for (var i = 0;i<object_list.length;i++){
    if (object_list[i]["user_id"] in user_ids){
        object_list.splice(i, 1);
    }
}

If it is an object, it could be done this way:

for (var i in object_list){
    if (object_list[i]["user_id"] in user_ids){
        delete object_list[i];
    }
}

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.