I have a JSON, which contains id and points. if the ID matches, i need to increase with 1. IF the id does not match i need to push to a new empty array
Here what I have tried. but it is not working
var points = [{
id: 1,
point: 0
}, {
id: 2,
point: 0
}, {
id: 3,
point: 1
}]
var data = {
id: 1
}
if (!(points.length)) {
points.push(data)
} else {
if (points.find(e => e.id === data.id)) {
var m = points.find(e => e)
console.log(m.id)
m.point+= 1
} else {
points.push(data)
}
}
You're always increasing the first element of the array
var m = points.find(e => e)
=>
var m = points.find(e => e.id === data.id)
find
need a predicate that return true or false given an element. In the first line, it always return the element itself which is a truthy value. So the first element is return
The find
method on array returns a value and not boolean
as you maybe are trying to use in this case. It'll return undefined
if no value matches.
Also you don't really need the outer if
and nest one more inside it.
var points = [{ id: 1, point: 0 }, { id: 2, point: 0 }, { id: 3, point: 1 }] var data = { id: 1 } let temp = points.find(e => e.id === data.id) if (temp != undefined) { // This is just for understanding. `undefined` inside `if` will give false. So you can use `if(!temp)` temp.point+= 1 } else { points.push(data) } console.log(points);
The new data needs a point property, and you could clean the code up a little to be clearer about intent...
var points = [{ id: 1, point: 0 }, { id: 2, point: 0 }, { id: 3, point: 1 }] var data = { id: 1 } // we have a data object. if it's new (not found in points) add it with a point count of 0 // if it exists (we find it in points array) increment point for the existing element let matchingPoint = points.find(p => p.id === data.id); if (!matchingPoint) { data.point = 0; points.push(data); } else { matchingPoint.point += 1; } console.log(points)
Creating an object:
tagObject = {};
tagObject['contentID'] = []; // adding an entry to the above tagObject
tagObject['contentTypes'] = []; // same explanation as above
tagObject['html'] = [];
Now below is the occurrences entry which I am addding to the above tag Object..
ES 2015 standards: function () {} is same as () => {}
let found = Object.keys(tagObject).find(
(element) => {
return element === matchWithYourValueHere;
});
tagObject['occurrences'] = found ? tagObject['occurrences'] + 1 : 1;
this will increase the count of a particular object key..
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.