is there a function in lodash to replace matched item
In your case all you need to do is to find object in array and use Array.prototype.splice()
method, read more details here:
var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
// Find item index using _.findIndex (thanks @AJ Richardson for comment)var index = _.findIndex(arr, {id: 1});
// Replace item at index using native splicearr.splice(index, 1, {id: 100, name: 'New object.'});
// "console.log" resultdocument.write(JSON.stringify( arr ));
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
Lodash: replace value in array of objects
You can use _.map
like below
const dataTwo = _.map(dataOne, item => ({...item, created_at: moment(item.created_at).format('MMM') }))
Plain JS or Lodash - replace object values with values from other object
With lodash you could do something like this with _.merge
, _.pick
and _.keys
:
let first = { a: 'John', b: 22, c: 'example'}, second = { b: 55, d: 'demo'}
let result = _.merge(first, _.pick(second, _.keys(first)))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
How to replace an object in object array in javascript (lodash)
you can do it with _.unionBy
var res = _.unionBy([obj], arr, 'id');
but check a note at this comment
How to merge objects with Lodash, but replace arrays values?
Use _.mergeWith()
, and if the 2nd value is an array, return it. If not return undefined
, and let merge handle it:
const oldValues = {"a":1,"b":[2,21,22,23],"c":{"d":3,"e":4,"f":[5,6,7]}};
const updatedValues = {"b":[],"c":{"f":[8]}};
const result = _.mergeWith(oldValues, updatedValues, (a, b) =>
_.isArray(b) ? b : undefined
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
is there a lodash function that is a combination of _.map() and _.filter()?
Just use map
and filter
:
arr = _.filter(
_.map(
$('.myDiv'),
el => $(el).attr('key')
),
key => key != 'default'
);
Related Topics
How to Delete a Query String Parameter in JavaScript
How to Update a Variable After Button Click
How to Change Color of Button on Press in React Native
Opening Pdf String in New Window With JavaScript
Google Script to See If Text Contains a Value
Javascript File Not Updating No Matter What I Do
How to Delete a Localstorage Item When the Browser Window/Tab Is Closed
Webpack: Module Not Found: Error: Can't Resolve (With Relative Path)
How to Change the Font Color, Font Size, and Button Color in React
How to Set a Header Field on Post a Form
Get the Contents of a Table Row With a Button Click
Angular2 Do Actions After Dom Has Finished Rendering
Trigger Event When Element Becomes Visible With Ngif
Call Js Function After Div Is Loaded
Javascript or Jquery Browser Back Button Click Detector