simon
simon

Reputation: 375

how to add object value after filter in javascript

How to add object value after filter out javascript

var arr = [{
  id: 1,
  username: 'fred'
}, {
  id: 2,
  username: 'bill'
}, {
  id: 3,
  username: 'ted'
}];

var obj = {
  id: 3,
  online: true
}

const result = arr.filter((item) => {
  if (item.id === obj.id) {
    return {
      item,
      online: obj.online
    }
  }
})

console.log(result)

It should be

{
          id: 3, 
    username: "ted", 
      online: true
}

Upvotes: 0

Views: 3088

Answers (3)

Kawser Habib
Kawser Habib

Reputation: 1422

According to this problem, Object.assign() is more suitable to solve this problem. One by one value assignment creates many boilerplate, needs more effort.

  • The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

  • Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones.

Code block:

var arr = [{
  id: 1,
  username: 'fred'
}, {
  id: 2,
  username: 'bill'
}, {
  id: 3,
  username: 'ted'
}];

var obj = {
  id: 3,
  online: true
}

function mergeObjByID(item) {
   if (item.id === obj.id){
    //overwrite item value 
    Object.assign(item,obj)
    return true
  }
}

const result = arr.filter(mergeObjByID); 

console.log(result)

More about Object.assign() example:

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

Upvotes: 0

danh
danh

Reputation: 62676

The OP expected output is a single object. filter() returns an array. find() finds the first object meeting the criterion returned by the predicate function. It's poor style for the predicate function to have a side-effect.

find() the object, then modify it.

const arr = [{
  id: 1,
  username: 'fred'
}, {
  id: 2,
  username: 'bill'
}, {
  id: 3,
  username: 'ted'
}];

var obj = {
  id: 93,
  online: true
}

const result = arr.find(item => item.id === obj.id)
result ? result.online = true : null
console.log(result)

Upvotes: 1

wangdev87
wangdev87

Reputation: 8751

Set item.online inside filter method.

var arr = [{
  id: 1,
  username: 'fred'
}, {
  id: 2,
  username: 'bill'
}, {
  id: 3,
  username: 'ted'
}];

var obj = {
  id: 3,
  online: true
}

const result = arr.filter((item) => {
  if (item.id === obj.id) {
    item.online = obj.online;
    return true;
  }
})

console.log(result)

Upvotes: 3

Related Questions