unable to insert a new key value pair to the existing pair - javascript

We have name value pair field in our table.These field can be modified i.e either existing values can be changed or a new pair might get added .
We have written the below script to update existing values .
Please help on how to add ,new pair to the existing .
for (var name in u_service_characteristics) {
if (parsed.service_characteristics[name] != null &&
parsed.service_characteristics[name] != undefined) {
u_service_characteristics[name] = parsed.service_characteristics[name];
}
}
Above code only modifies the existing names ,how to insert if the incoming name doesnt exist.

I am guessing this is what you need
var existings = Object.getOwnPropertyNames(u_service_characteristics);
for (var name in parsed.service_characteristics) {
if (!existings.includes(name)) {
u_service_characteristics[name] = parsed.service_characteristics[name];
}
}

Instead of iterating over the keys of the target, just iterate over the keys of the source:
for(var name in parsed.service_characteristics)

Related

How to check if item already exists in object array?

I would like to check if an item.name already exists in the object array so it will not push that existing object to the array.
This is the piece of code:
loadedVariations.forEach(function(item){
console.log('item', item.name.indexOf(name));
if(name === tests[test].id && item.name.indexOf(name) < 0){
console.log(item.name)
loadedVariations.push({name: name, variation: variation});
tests[test].callback(name, variation);
console.log('tests', tests[test], variation, loadedVariations);
if(variation === '1'){
value = "control"
} else {
value = "variationb"
}
localStorage.setItem('gtmTest', JSON.stringify(loadedVariations));
}
})
This is the output in my localstorage:
gtmTest:
[{"name":"globalPassFrame_review","variation":"1"},
{"name":"globalPassFrame_review","variation":"1"},
{"name":"socialshare_bar","variation":"2"},
{"name":"socialshare_bar","variation":"2"}]
This is an AB Test in google tag manager with an helping script which runs on multiple test scripts so it runs multiple times that's why I need to check if item already exists in the object array so it doesn't push the same object twice.
Here is how do you can iterate over your json object by using every and match name . If you want to have array of unique Names you can iterate using forEach and check if it is not present in array .
var object = [{"name":"globalPassFrame_review","variation":"1"},{"name":"globalPassFrame_review","variation":"1"},{"name":"socialshare_bar","variation":"2"},{"name":"socialshare_bar","variation":"2"}];
var tobeFound='globalPassFrame_review';
object.every(function (elem, i) {
if(elem.name == tobeFound ){
console.log('element found at index '+i);
return false ;
}
});
// In case you want to store uniue Names
var uniqueNames=[];
object.forEach(function (elem, i) {
if(!uniqueNames.includes(elem.name)){
uniqueNames.push(elem.name);
}
});
console.log(`unique Names are ${uniqueNames}`);
// Using ES6 style of code.
const uniqueNamesArr = [...new Set( object.map(obj => obj.name)) ];
console.log(uniqueNamesArr);

Redis key is not creating properly

I am new to Redis and am trying to hmset some values by generating my own keys to store and access it. But for some reason, key is not being created properly and the data's are overwritten. Below is my code for it,
locations.forEach(function(location) {
var key = location.id;
console.log(key); // all keys are correct
client.hmset("locations", { key: location }); // using redis-jsonify
});
The data am getting is only one of the whole response since the key is actually saved as key itself.
For example:
I tried using client.incr('id', function(err, id) {}); but same problem.
Need help with this. Thanks in advance.
From the Redis HMSET doc:
Sets the specified fields to their respective values in the hash
stored at key. This command overwrites any existing fields in the
hash. If key does not exist, a new key holding a hash is created.
HMSET is used to set all the values at once.
If you want to set one hash field at a time, use HSET:
locations.forEach(function(location) {
var key = location.id;
client.hset("locations", key, location); // or `JSON.stringify(location)` if redis-jsonify doesn't work as expected
});
Closures to resuce
for (var i = 0; i < locations.length; i++) {
(function(i) {
console.log('locations: ' + location[i]);
client.hmset("locations", { i: location[i] });
})(i);
}

How to reset object value to null in angularjs?

This is my code
var data={};
data={stdId:"101"};
data={empId:"102"};
data={deptId:"201"};
I have a data object getting data from services with one key only. but key names are different like stdId or empId ,etc.
I want to assign empty value to stdId or empId ,etc. like data={stdId:""} .
The key names are changed dynamically based on services.
Not entirely sure what you are trying to achieve, but if you know the name of the property you could use:
data['stdId'] = '';
or
data.stdId = '';
If you do not know the property name, but you still want to keep the property names on the object you could use:
for(var prop in data) {
if(data.hasOwnProperty(prop)) {
data[prop] = '';
}
}
You can use for..in loop to iterate over data object using key.
for(var key in data){
if(data.hasOwnProperty(key)){
data[key] = '';
}
}
Note: This will set every property of data object to ''
data.stdId = null;
or
data.stdId = '';
or
data = { stdId };
Have you tried those?
As I understand your question, you won't know the name of the key in each object and there is only ever one. To solve your problem:
data[Object.keys(data)[0]] = ''
This will assign the value of the key to null.

access javascript array element by JSON object key

I have an array that looks like this
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}]
I would like to be able to access the Count property of a particular object via the Zip property so that I can increment the count when I get another zip that matches. I was hoping something like this but it's not quite right (This would be in a loop)
Zips[rows[i].Zipcode].Count
I know that's not right and am hoping that there is a solution without looping through the result set every time?
Thanks
I know that's not right and am hoping that there is a solution without
looping through the result set every time?
No, you're gonna have to loop and find the appropriate value which meets your criteria. Alternatively you could use the filter method:
var filteredZips = Zips.filter(function(element) {
return element.Zip == 92880;
});
if (filteredZips.length > 0) {
// we have found a corresponding element
var count = filteredZips[0].count;
}
If you had designed your object in a different manner:
var zips = {"92880": 1, "91710": 3, "92672": 0 };
then you could have directly accessed the Count:
var count = zips["92880"];
In the current form, you can not access an element by its ZIP-code without a loop.
You could transform your array to an object of this form:
var Zips = { 92880: 1, 91710: 3 }; // etc.
Then you can access it by
Zips[rows[i].Zipcode]
To transform from array to object you could use this
var ZipsObj = {};
for( var i=Zips.length; i--; ) {
ZipsObj[ Zips[i].Zip ] = Zips[i].Count;
}
Couple of mistakes in your code.
Your array is collection of objects
You can access objects with their property name and not property value i.e Zips[0]['Zip'] is correct, or by object notation Zips[0].Zip.
If you want to find the value you have to loop
If you want to keep the format of the array Zips and its elements
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}];
var MappedZips = {}; // first of all build hash by Zip
for (var i = 0; i < Zips.length; i++) {
MappedZips[Zips[i].Zip] = Zips[i];
}
MappedZips is {"92880": {Zip: 92880, Count:1}, "91710": {Zip:91710, Count:3}, "92672": {Zip:92672, Count:0}}
// then you can get Count by O(1)
alert(MappedZips[92880].Count);
// or can change data by O(1)
MappedZips[92880].Count++;
alert(MappedZips[92880].Count);
jsFiddle example
function getZip(zips, zipNumber) {
var answer = null;
zips.forEach(function(zip){
if (zip.Zip === zipNumber) answer = zip;
});
return answer;
}
This function returns the zip object with the Zip property equal to zipNumber, or null if none exists.
did you try this?
Zips[i].Zip.Count

If value is found, take another value from same object

Can anyone tell me if it is possible ?
Basically, I want to search through an array of json objects, and if I find a specific value in one of them, I want to take other values from the same object.
Thanks
var myArrayObject = $.parseJSON(<string>);
for(var i = 0;i <myArrayObject.length; i++){
if (myArrayObject[i] == "<your specified value>") {
// your code here
}
}

Categories

Resources