const posts = [
{ id : 1 , upVotes : 2 } ,
{ id : 2 , upVotes : 89 } ,
{ id : 3 , upVotes : 1 }
] ;
const totalUpVotes = posts . reduce ( ( acc , curr ) => {
return acc + curr . upVotes
} , 0 )
console . log ( totalUpVotes ) // 92
const users = [
{ id : 1 , name : "Foo" } ,
{ id : 2 , name : "Bar" } ,
{ id : 3 , name : "FooBar" }
] ;
const mappedUser = users . map ( ( user ) => {
return {
id : user . id + 100 ,
name : user . name
}
} ) ;
console . log ( mappedUser ) // [ {id: 101, name: "Foo"}, {id: 102, name: "Bar"}, {id: 103, name: "FooBar"}];
const users = [
{ id : 1 , name : "Foo" , isActive : true } ,
{ id : 2 , name : "Bar" , isActive : false } ,
{ id : 3 , name : "FooBar" , isActive : true }
] ;
const activeUsers = users . filter ( ( user ) => {
return user . isActive
} )
console . log ( activeUsers ) // [{"id":1,"name":"Foo","isActive":true},{"id":3,"name":"FooBar","isActive":true}]
Adding an element to an array of objects
const users = [
{ id : 1 , name : "Foo" } ,
{ id : 2 , name : "Bar" }
] ;
const newUsers = [ ...users , { id : 3 , name : "FooBar" } ]
console . log ( newUsers ) // [{"id":1,"name":"Foo"},{"id":2,"name":"Bar"},{"id":3,"name":"FooBar"}]
Adding a key value pair to an object
const users = { id : 1 , name : "Foo" } ;
const newUsers = { ...users , isActive : true }
console . log ( newUsers ) // {"id":1,"name":"Foo", isActive: true}
Adding a key value pair with dynamic key
const dynamicKey = "hasSmartPhone" ;
const users = { id : 1 , name : "Foo" } ;
const newUsers = { ...users , [ dynamicKey ] : false }
console . log ( newUsers ) // {"id":1,"name":"Foo", hasSmartPhone: true}
Find and replace key value pair in array of objects
const posts = [
{ id : 1 , title : 'Title 1' } ,
{ id : 2 , title : 'Title 2' }
] ;
const updatedPost = posts . map ( ( post ) => {
return post . id === 1 ? { ...post , title : "Updated Title 1" } : post
} )
console . log ( updatedPost ) // [{"id":1,"title":"Updated Title 1"},{"id":2,"title":"Title 2"}]
Find an element inside an array of objects
const posts = [
{ id : 1 , title : 'Title 1' } ,
{ id : 2 , title : 'Title 2' }
] ;
const postInQuestion = posts . find ( p => p . id === 2 ) ;
console . log ( JSON . stringify ( postInQuestion ) ) // {id: 2, title: 'Title 2'}
Delete a key value pair inside an object
const users = { id : 1 , name : 'foo' , password : "foo@123" } ;
const userWithoutPassword = ( ( { id, name } ) => {
return ( { id, name } ) //{ id : id, name: name }
} ) ( users )
console . log ( userWithoutPassword ) // {id: 1, name: 'foo'}