简体   繁体   中英

Filter through objects array and remove items

I have an array of objects in angularjs looking like this:

[
   0: {id: "1", user_id: "1", name: "object1"},
   1: {id: "2", user_id: "1", name: "obejct2"},
   2: {id: "3", user_id: "2", name: "object3"},
]

I want to search through the array and remove the items that don't have a specific user_id, stored in another variable. I tried array.filter but didn t work.

array.filter is the correct approach. You probably miss-implemented it.

See this snippets, it filters out all entries with a user_id different from 1

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

 const data = [ {id: "1", user_id: "1", name: "object1"}, {id: "2", user_id: "1", name: "object3"}, {id: "3", user_id: "2", name: "object3"}, ] const filteredData = data.filter((item) => { return item.user_id === '1'; }) console.log(filteredData) 

Lets say you store the selected value into 'selectedUserId' variable.

You can achieve your goal by:

 let selectedUserId = '1'; let data = [ {id: "1", user_id: "1", name: "object1"}, {id: "2", user_id: "1", name: "object3"}, {id: "3", user_id: "2", name: "object3"}, ] let output = data.filter(item => item.user_id === selectedUserId) console.log(output) 

Thought I would add a nicely concise way:

const keepId = '1'
const filtered = data.filter(({ user_id }) => user_id === keepId)

Uses:


Also keep in mind that filter() returns a new array, keeping the original in tact. If you want to alter the original array, you would have to use something like splice()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM