Changing specific array value using Javascript - javascript

I currently have the following array in javascript
var chart1data = [
{ "Time": "1", "Temperature": 60, },
{ "Time": "2", "Temperature": 50, },
{ "Time": "3", "Temperature": 42, },
{ "Time": "4", "Temperature": 35, },
{ "Time": "5", "Temperature": 28, },
{ "Time": "6", "Temperature": 24, },
{ "Time": "7", "Temperature": 21, },
{ "Time": "8", "Temperature": 19, },
{ "Time": "9", "Temperature": 18, },
{ "Time": "10", "Temperature": 18, },
];
I have a button, in my HTML which when pressed, should change the value "60" in the above array to another number (for example - 80)
The button links to this function. How can I make it so this works?
function updatechart (){
//This gets the number from a text box
var inputdata1 = document.getElementById("textbox1").innerHTML
//Now I need the code to put this number in replace of the value "60"
}

You can update your array as follows:
chart1data[index].Temperature = inputdata1;
Fiddle: http://jsfiddle.net/KyleMuir/sPTG8/1/
Hope this helps

if you want to change 60 then:
chart1data[0].Temperature = inputdata1;
else
chart1data[index].Temperature = inputdata1;

Simply put, you have an array of object. Said objects contain 2 properties, Time and Temperature. To access an object within the array, assuming you know the index, you can do:
alert(chart1data[index].Time) // alerts the time of the first item
chart1data[index].Temperature = 60; // sets the temperature of the first item
Alternatively, if you want to replace all temperature values that are 60, you can loop through your items and simply update them, like so:
for (var i = 0; i < chart1data.length; i++) {
if (chart1data[i].Temperature == '60') {
chart1data[i].Temperature = '80'
}
}

Related

Javascript: Merge Array of Objects, summing values with same key

I already searched for my issue, however, i did not find something, that matches my needs. I want to merge (sum) multiple series of data into a single array. Any dataset that matches the key, shall be summed in the resulting array.
Please see sample data and expected result:
var power1 = [
{
"time": 10,
"power": 100
},
{
"time": 20,
"type": 200
},
{
"time": 30,
"type": 300
}
]
var power2 = [
{
"time": 20,
"type": 200
},
{
"time": 30,
"type": 300
},
{
"time": 40,
"type": 400
}
]
var result = [
{
"time": 10,
"type": 100
},
{
"time": 20,
"type": 400
},
{
"time": 30,
"type": 600
},
{
"time": 40,
"type": 400
}
]
Since this should happen with thousands of items, it should be reasonable fast. Could a Map as intermediate help here?
Thanks in advance
You can concat the two arrays and then perform a reduce operation over it with an object to store the values for each key.
var power1=[{time:10,type:100},{time:20,type:200},{time:30,type:300}],power2=[{time:20,type:200},{time:30,type:300},{time:40,type:400}];
const res = Object.values(
power1.concat(power2).reduce((acc, {type, time})=>{
(acc[time] ??= {time, type: 0}).type += type;
return acc;
}, {})
);
console.log(res);

Find value of an object in json, node.js

I need a way to find the kills and deaths (etc.) of the corresponding name that is inputted, and if the name is not in the object I need it to output something too.
Something like this:
if (medic does not have(name)) return;
const kills = medic.(name).kills
Sample JSON:
{
"assault": {
"general": {
"kills": 1134,
"deaths": 1122,
"abc": "123"
},
"list": {
"A": {
"name": "name1",
"kills": 12,
"deaths": 120
},
"B": {
"name": "name2",
"kills": 23,
"deaths": 53
}
}
},
"support": {
"general": {
"kills": 123,
"deaths": 11232,
"abc": "11233"
},
"list": {
"A": {
"name": "name4",
"kills": 12,
"deaths": 120
},
"B": {
"name": "name5",
"kills": 23,
"deaths": 53
}
}
}
}
First clean your data to get a nice list of the names and info:
const listOfNames = [...Object.values(data.assault.list), ...Object.values(data.support.list)]
Then use the find method on that list to search for a name, with the backup of "Not Found" if the search returns undefined:
const search = (name) => listOfNames.find(item => item.name===name) || "Not Found"
Then you can use that search function elsewhere:
console.log(search("name2")) gives
See it in action here:
https://repl.it/#LukeStorry/62916291
Do you need assault and support to be sum up or all you need is one of those? Is your data always on the same shape? I'm going to assume that it is, and I'll provide both, the sum and the individual one:
const data = // your JSON here
const getAssaultKills = name => (data.assault.list[name] || {kills: 0}).kills
const getSupportKills = name => (data.support.list[name] || {kills: 0}).kills
const getTotalKills = name =>
getSupportKills(name) + getAssaultKills(name)
getTotalKills("A") // => 24
getTotalKills("C") // => 0

Make v-card selectable/toggle-able and pass an object to an array in Vue

I currently have some cards that each hold a value. I want to basically make each card act like a toggle button and when the card is toggled on I want that cards value to be added to the array.
I currently use:
#click="selectableCards( {Group: `${user.GroupHex}`, UserID: user.UserIDInt, SuperID: `${user.SuperID}`} )"
to pass the data to my function:
selectableCards(x) {
if(this.array.includes(x)) {
console.log('prop already exists inside array')
} else {
this.array.push(x)
}
console.log(this.array)
}
Whenever I use this the object is added to the array but it will allow me to add the same object over and over again. It doesn't detect that the object is already in the array.
So again basically I want the #click on the card to act like a toggle button to add or remove the data inside the card.
An example of 3 cards values into an array:
[ { "Group": "10", "UserID": 6, "SuperID": "2566" }, { "Group": "10", "UserID": 5, "SuperID": "2565" }, { "Group": "20", "UserID": 9, "SuperID": "5129" } ]```
You cannot cannot compare objects same way as primitives in javascript:
const objects = [ { "Group": "10", "UserID": 6, "SuperID": "2566" }, { "Group": "10", "UserID": 5, "SuperID": "2565" }, { "Group": "20", "UserID": 9, "SuperID": "5129" } ]
console.log(objects.includes({ "Group": "10", "UserID": 6, "SuperID": "2566" }))
For more information about that take a look here: Object comparison in JavaScript
However what you can do is to search for an element in an array based on some conditions for example with array.find() -method like so:
const objects = [ { "Group": "10", "UserID": 6, "SuperID": "2566" }, { "Group": "10", "UserID": 5, "SuperID": "2565" }, { "Group": "20", "UserID": 9, "SuperID": "5129" } ];
const matchedObject = objects.find((object) => {
return object.Group === "10" &&
object.UserID === 6 &&
object.SuperID === "2566"
});
console.log(matchedObject);
If you just need to know if a card is selected send a string/number to selectableCards instead of an object and your function doesn't have to change.
#click="selectableCards(user.UserID)"
OR
#click="selectableCards(user.SuperID)"
If however you need to store the object I would recommend using findIndex instead of includes
if(this.array.findIndex(temp => {
return temp.Group == x.Group && temp.UserID == x.UserID && temp.SuperID == x.SuperID
})>-1)
...the rest of the code is unchanged

Multiply the object properties

someone tell me how to multiply object's properties? I need this object multiplied by the count of property price and put together
var menu = [
{
"id": 5,
"price": 13,
"count": 2
},
{
"id": 8,
"price": 7,
"count": 3
},
{
"id": 9,
"price": 17,
"count": 1
}
]
var sum = 0;
for (var key in menu) {
for (var key1 in menu[key]) {
//console.log(key1);
if (key1 == 'price'){
price += menu[key][key1];
}
}
}
but I have no idea how to multiply count property
You can use Array.prototype.map with Array.prototype.reduce.
.map takes a callback function which will multiply the price of each item by the count and creates a new array looking like this:
[26,21,17].
.reduce takes a callback as well, iterating over the new create array summing up the multiplied prices resulting to:
64
let menu = [
{
"id": 5,
"price": 13,
"count": 2
},
{
"id": 8,
"price": 7,
"count": 3
},
{
"id": 9,
"price": 17,
"count": 1
}
]
let sum = menu.map(p => p.price * p.count).reduce((a,b) => a + b)
console.log("Total:",sum)
You probably want something like this:
{
"id": 5,
"price": 13,
"count": 3,
"value": function() {return this.price * this.count;}
}
You can do that by either making an object and adding a prototype (which saves memory and time) or construct it that way each time.
Otherwise you can just do:
var obj = { ... } // your stuff
alert(obj.price * obj.count)
suppose you want to calculate the sum
var menu = [
{
"id": 5, "price": 13, "count": 2 }, {
"id": 8, "price": 7, "count": 3 }, { "id": 9, "price": 17, "count": 1 } ];
var sum = 0, item;
for(item in menu)
{
sum += menu[item].price * menu[item].count;
}
console.log(sum);

Looping through unnamed array objects with backbone and dust

I have a JSON formed like you can see further below. I am having trouble looping through and defining the correct points to loop over, as I'm not that experienced with arrays in objects and complicated JSON.
What I'm mainly looking for is some pointers on the parse / toJSON parts of my collection, or other places I might be failing with this particular structure.
I am trying to loop over the values and output data from the event and the type name using backbone and dust. Normally I can just loop over my JSON by defining the collection in the view, e.g. calling this like so:
dust.render("dialog-decoderevents-items", { events : currentUser.eventList.toJSON() }, function(err, out) {
_this.$(".ab-tvg-prg-opt-future").append($(out));
});
That would normally allow me to just make a loop in dust and output data like this:
{#events}
{#tvProgram}{name}{/tvProgram}
{type}
{/events}
I have tried the dust examples using array and current context on this JSON and it will output something with no problem. I think the problem lies in what I define as the starting point of the model and collection.
I have both a parse function and a toJSON function in my collection now. But I also don't know what to define as an id on the model, since as you can see the id is defined inside the event, and not on the outside where I'd normally use it. Ideas? All the data is below.
JSON
{
"status": null,
"value": [
{
"event": {
"id": "RWtzdHJlbSBvcHBkcmFnZWxzZTxsZHR2cGQ+MTM2NDMwMDQwMDAwMDxsZHR2cGQ+MTM2NDMwNDAwMDAwMA==",
"name": "A glorious event",
"description": "Some long description about the event",
"startTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 13,
"minute": 20,
"seconds": 0
},
"endTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 14,
"minute": 20,
"seconds": 0
}
},
"type": "Party"
},
{
"event": {
"id": "Rmx5aW5nIFdpbGQgQWxhc2thPGxkdHZwZD4xMzY0MzA2NDAwMDAwPGxkdHZwZD4xMzY0MzEwMDAwMDAw",
"name": "A glorious event",
"description": "Some long description about the event",
"startTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 15,
"minute": 0,
"seconds": 0
},
"endTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 16,
"minute": 0,
"seconds": 0
}
},
"type": "Birthday"
},
{
"event": {
"id": "UG9pcm90PGxkdHZwZD4xMzY0MzE2NjAwMDAwPGxkdHZwZD4xMzY0MzE5NjAwMDAw",
"name": "A glorious event",
"description": "Some long description about the event",
"startTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 17,
"minute": 50,
"seconds": 0
},
"endTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 18,
"minute": 40,
"seconds": 0
}
},
"type": "Birthday"
},
{
"event": {
"id": "VGhlIEJpZyBCYW5nIFRoZW9yeTxsZHR2cGQ+MTM2NDMxOTAwMDAwMDxsZHR2cGQ+MTM2NDMyMDgwMDAwMA==",
"name": "A glorious event",
"description": "Some long description about the event",
"startTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 18,
"minute": 30,
"seconds": 0
},
"endTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 19,
"minute": 0,
"seconds": 0
}
},
"type": "Birthday"
}]}
Model
var mainEvent = Backbone.Model.extend({
idAttribute : "id",
defaults : {
type: null,
event : {
id : null,
name: null,
description: null,
channelId: null,
startTime: null,
endTime: null
}
}
});
Collection
var eventCollection = Backbone.Collection.extend({
model: mainEvent,
parse : function(json, options) {
var retr = [], tmp;
if (json.status === ajaxStatus.success) {
switch(options.action) {
default:
retr = json.value;
break;
}
if (options.action === "events") {
currentUser.eventList = new eventCollection(retr, { action : "events" });
}
}
else if (json.status === ajaxStatus.notAuthenticated) {
currentUser.trigger("notLoggedIn");
return [];
}
return retr;
},
toJSON : function(){
var ret = this.constructor.__super__.toJSON.call(this);
// _.each(ret, function (item) {
// console.log('l1'+item);
// ret.push(item);
// });
return ret;
}
});
Idea after quickly reading over your issue (take it with a grain of salt as I've never used dust or backbone before):
Couldn't you just create a controller that stores a content array for each event object? That way, all you would have to do when you were extracting the JSON file is add each event to the controller, and iterate over that in your HTML. You could then extract the id with id = event[id] or something.
EDIT: Here's an example with AJAX, I know you're not using that but the parsing bit should at least be helpful:
function getParties() {
$.ajax({
url: 'json/party.json',
dataType: 'json',
async: false,
success: function(data) {
console.log("Data:", data.value);
for (var i=0, occurence; occurence = data.value[i]; i++) {
var event = {};
event.type = occurence.type;
for (var key in occurence.event) {
event[key] = occurence.event[key];
}
console.log("Event:", event);
// Do something with event... Maybe add to content array.
}
}
});
}
The "event" should now be in simple javascript. If you want to access a known field within it, you can say event["id"] for example. To iterate through all values, use the following loop.
for (var key in event) {
console.log("Key: " + key + ", Value: " + event[key]);
}
You also should be able to get the value with {id}, for example, in Backbone. Something similar works in Ember when the created "event" objects are pushed to some controller's content array, which is what I'm using.

Categories