Javascript - push into JSON array - javascript

Just trying to update a JSON array and hoping for some guidance.
var updatedData = { updatedValues: [{a:0,b:0}]};
updatedData.updatedValues.push({c:0});
That will give me:
{updatedValues: [{a: 0, b: 0}, {c: 0}]}
How can I make it so that "c" is part of that original array?
So I end up with {a: 0, b: 0, c: 0} in updatedValues?

You actually have an object inside your array.
updatedData.updatedValues[0].c = 0;
will result in your desired outcome.

The updatedValues is a plain object and you have to add c as property.
var updatedData = { updatedValues: [{a:0,b:0}]};
updatedData.updatedValues[0]["c"] = 0;
If you are using jquery then do as follows.
var updatedData = { updatedValues: [{a:0,b:0}]};
$.extend(updatedData.updatedValues[0],{c:0});

You're pushing something to the updated values array, rather than setting an attribute on the 0th element of the array.
updatedData.updatedValues[0].c = 0;

You can add an item in the object.
This should work.
updatedData.updatedValues[0]['c']=0;

Related

How to access js objects where keys aren't known

How to access object elements in the example below where the keys are unknown
var person={{name:"john",username:"clap"},{name:"sandr",username:"poss"}}
Any help would be appreciated
This might help you. You can use a for...in loop to loop over the keys or values of an object.
var obj = {a: 1, b: 2, c: 3};
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

Replace an element of an object by one of its own sub-elements

Let's say I have:
let list = [{a: {b: 'foo'}}, {a: {b: 'bar'}}]
I want to end up with:
list = [{a: 'foo'}, {a: 'bar'}]
This works:
list = list.map(d => {d.a = d.a.b; return d})
But I have a bad feeling that changing the value in place is a bad idea.
Is there a cleaner way? is my solution actually valid?
You could use Array#forEach and change the object in situ, because you need not to return a new array, while you already mutate the original object of the array.
let list = [{ a: { b: 'foo' } }, { a: { b: 'bar' } }];
list.forEach(d => d.a = d.a.b);
console.log(list);
It is not changing the value in place.
map method only creates a new array by applying a callback provided function for every item in the array.
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
For changing the value in place you can use forEach method.

Inserting an object so the array stays sorted

I have an enum of different Steps
export enum StepCategory {
START = 0,
POSITION_1 = 1,
TRANSPORT = 2,
RECEIVER = 3,
END = 4,
NO_STEP_MATCH = 5
}
This will later result in an array, where for every Step I have an object. The Problem is I won't load all the information at once, so i can'tdo a simple for-loop and push each item chronogically. I could be that I first load the value for Step 4, so my array would be:
var array = [{"END" , "POSITIVE"}]
Afterwards I would get the Info for Step 2, then I would have:
var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]
But this is not sorted.
What should I do? Should I declare an array of 6 undefined values
var array = [undefined, undefined, undefined, undefined, undefined, undefined]
This way I wouldn't need any sorting-algorithm after each Update, and can just push the value at the right position.
Just some small Info: I use AngularJS 1, Typescript and Lodash
In plain Javascript, you could sort it with an object and the assigned values of the key.
var StepCategory = { START: 0, POSITION_1: 1, TRANSPORT: 2, RECEIVER: 3, END: 4, NO_STEP_MATCH: 5 },
array = [["END", "POSITIVE"], ["TRANSPORT", "POSITIVE"]];
array.sort(function (a, b) {
return StepCategory[a[0]] - StepCategory[b[0]];
});
console.log(array)
First of all, this is - as someone mentioned in the comments - not syntactically correct:
var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]
I assume that this was just a typo writing this question. Additionally if you actually use the enum in your array as key and just left it out for demonstration purposes, I would expect your array of objects to look something like this:
var array = [{StepCategory.END: "POSITIVE"}, {StepCategory.TRANSPORT: "POSITIVE"}]
In order to sort this with LoDash you could use something like this:
var sortedArray = _.sortBy(array, i => Object.keys(i)[0]);
This sorts your array by the value of the first key of each object which refers to your enum value.

removing the key from a key value pair of objects in javascript

Let's say I have this Array of objects:
[300: {a:"some", b:"value"}, 301: {a: "another", b: "val"} ...]
I have that kind of object and I am iterating using recursive function, and there's no way I will change my counter to start at 300, I always start at 0.
I am thinking of a solution, to remove the keys from the agrray so that I will have an array like so:
[{a:"some", b:"value"}, {a: "another", b: "val"} ...]
How do I do that in javascript? Also, if there is another way that would be much faster than creatng a function that will remove keys, it will be much better.
This will give you a syntax error (SyntaxError: missing ] after element list):
var data = [300: {a:"some", b:"value"}, 301: {a: "another", b: "val"}];
You mean this:
var data = {300: {a:"some", b:"value"}, 301: {a: "another", b: "val"}};
And to convert that into an array, loop over the object and push each value into a new array:
var arr = [];
for (var k in data) {
arr.push(data[k]);
}
Fiddle
If you meant that the initial structure of array is this:
var data = [{300: {a:"some", b:"value"}}, {301: {a: "another", b: "val"}}];
then this should work (result array):
var result = [];
var data = [{300: {a:"some", b:"value"}}, {301: {a: "another", b: "val"}}];
for(var i =0; i < data.length; i++){
for(var key in data[i]) {
if(data[i].hasOwnProperty(key)) {
result.push(data[i][key]);
break;
}
}
}
There is a point here that should be clarified. When you have a Array object which its values starts from 300 as its indexes, it means you have 300 indexes with undefined values, but if it is just an Array-like object it could be totally different.
Let's say this is not an Array-like and is an actual Array, so you have to filter it so that all the undefined values get removed from your array, so your array should be like:
var arr = [/*0*/undefined, ..,/*299*/undefined, /*300*/{a:"some", b:"value"}, /*301*/ {a: "another", b: "val"} ...]
var result = arr.filter(function(value,index){
return (value !== undefined);
});
but what you have mentioned in your question, is more likely a javascript object, so to do what you want you can do:
var myObj = {300: {a:"some", b:"value"}, 301: {a: "another", b: "val"} };
var result = {};
for(var key in obj){
if(obj.hasOwnProperty(key)){
result.push(obj[key]);
}
}
in this for loop hasOwnProperty function helps you make sure if it is one of the actual object values, and not other possible keys from the object's prototype chain.

Mapping multiple keys to the same value in a Javascript hash

I use a Javascript hash object to store a set of numerical counters, set up like this [this is greatly simplified]:
var myHash = {
A: 0,
B: 0,
C: 0
};
Is there a way to make other keys, ones not explicitly in myHash, map to keys that are? For instance, I'd like [again, this is simplified]:
myHash['A_prime']++; // or myHash.A_prime++;
to be exactly equivalent to
myHash['A']++; // or myHash.A++;
e.g. incrementing the value found at the key A, not A_prime.
Assuming there aren't any valid string values in this hash, you could create your own mapping of keys to other keys, within the hash itself, and wrap the key/value pairs in your own function, as follows:
var hash = {
A: 0,
B: 0,
C: 0,
A_asdf: 'A',
B_asdf: 'B',
A_another: 'A'
}
function increment(key)
{
// iteratively find the real key
while (typeof(hash[key]) == 'string')
{
key = hash[key];
}
hash[key]++;
}
A way of solving this would be wrapping all values in an object, and use this object in several keys.
var myHash = {
A: {value: 0},
...
};
myHash['A_prime'] = myHash['A'];
myHash['A_prime'].value++;
I think you would be better off just writing a function to accomplish the incrementation of one hash array or multiple depending on what you are trying to accomplish. I may have not understood the question correctly but this is my solution.
var smallHash = {
A: 0,
B: 0,
C: 0,
A_prime:'A',
B_prime:'B',
C_prime:'C'
};
function incrementPrime(myHash,key)
{
letterKey = myHash[key];
myHash[letterKey]++;
}
incrementPrime(smallHash,'C_prime');
alert("C is now: "+smallHash['C']); // should return 1
You could act on the key, instead of the hash:
var myHash = {
A: 0,
B: 0,
C: 0
};
function incr(prop){
myHash[prop[0]]++;
}
incr('A');
incr('A_asdf');
The function incr could be anything else you want to apply to the hash.
As described, no. If you can change your keys to objects though you'd get closer:
var x = new Object();
var y = x;
myHash[x] = 1;
myHash[y]++; // should increment the value since y is x.

Categories

Resources