javascript update or add values to array - javascript

I want to add values to array. But the same values may update. for example my array is
[{"abc1":"123456"},{"abc2":"123456"}]
when is adding again is abc1. It may update. For example in normal case
[{"abc1":"123456"},{"abc2":"123456"},{"abc1":"123456"}]
But i want
[{"abc2":"123456"},{"abc1":"123456"}]
My code
var categories = [],
arrIndex = {};
addOrReplace({"abc1":"125"});
addOrReplace({"abc2":"126"});
addOrReplace({"abc1":"127"});
addOrReplace({"abc3":"129"});
function addOrReplace(object) {
var index = arrIndex[object[0]];
console.log("index:"+object[0]);
if(index === undefined) {
index = categories.length;
}
arrIndex[object[1]] = index;
categories[index] = object;
}
console.log(categories);
It not showing correct answer.
It shows
[{"abc3":"129"}]
I want
[{"abc2":"126"},{"abc1":"127"},{"abc3":"129"}]
How it possible? Please help me?

You could use Array#findIndex ans plice the object from categories if the index is found, then push the new object to categories.
function addOrReplace(object) {
var key = Object.keys(object)[0],
index = categories.findIndex(o => key in o);
if (index !== -1) {
categories.splice(index, 1);
}
categories.push(object)
}
var categories = [];
addOrReplace({ abc1: "125"});
console.log(categories);
addOrReplace({ abc2: "126"});
console.log(categories);
addOrReplace({ abc1: "127"});
console.log(categories);
addOrReplace({ abc3: "129"});
console.log(categories);
.as-console-wrapper { max-height: 100% !important; top: 0; }

var categories = new Map();
addOrReplace({"abc1":"125"});
addOrReplace({"abc2":"126"});
addOrReplace({"abc1":"127"});
addOrReplace({"abc3":"129"});
function addOrReplace(object) {
for (var name in object)
categories[name] = object;
}
console.log(categories);

var categories = [],
arrIndex = {};
addOrReplace({"abc1":"125"});
addOrReplace({"abc2":"126"});
addOrReplace({"abc1":"127"});
addOrReplace({"abc3":"129"});
function addOrReplace(object) {
for(var c in categories){
if(Object.keys(categories[c])[0] == Object.keys(object)[0]){
categories.splice(c,1)
}
}
categories.push(object)
}
console.log(categories);
//[{"abc2":"126"},{"abc1":"127"},{"abc3":"129"}]

I don't know how you would be finally using the final data but in case you are looking for the uniqueness, i would like to recommend to go for object hash instead of array.
Initially :
{
"abc1" : "123456",
"abc2" : "123456"
}
If you now add { "abc1" : "some_other_value" }.
{
"abc1" : "some_other_value",
"abc2" : "123456"
}
You can also check if the value exist already or not using if(objectHash('abc1')).
It can save you from extra traversal and would overwrite values if already present.

Related

Checking for an item in an array

I'm having trouble finding the right way to find if an item from a for loop is in an array. Let's say I have a for loop that is iterating through some results. If they are in an array:
ctids = [];
continue to the next step in the for loop, but if not, push them to the array and do something else. What is the correct syntax for this?
for (var i=0;i<results.features.length;i++){
ACS_BG = results.features[i].attributes.BLKGRPCE;
ACS_ST = results.features[i].attributes.STATEFP;
ACS_CNTY = results.features[i].attributes.COUNTYFP;
ACS_TRCT = results.features[i].attributes.TRACTCE;
if ACS_TRCT exists in ctids { //This is where I am having trouble.
continue; //skip the rest of the if statement
} else {
ctids.push(ACS_TRCT);
// do something else;
};
};
Can you please try this code
var ctids = []
for (var i=0;i<results.features.length;i++){
ACS_BG = results.features[i].attributes.BLKGRPCE;
ACS_ST = results.features[i].attributes.STATEFP;
ACS_CNTY = results.features[i].attributes.COUNTYFP;
ACS_TRCT = results.features[i].attributes.TRACTCE;
if(!ctids.includes(ACS_TRCT))
{
ctids.push(ACS_TRCT);
}
};
You can use includes to check if the elment exist in array and if not push the element into it.
if (ctids.includes(ACS_TRCT)){
continue;
}else{
ctids.push(ACS_TRCT)
}
I'd do:
for (var i = 0; i < results.features.length; i++) {
const ACS_BG = results.features[i].attributes.BLKGRPCE;
const ACS_ST = results.features[i].attributes.STATEFP;
const ACS_CNTY = results.features[i].attributes.COUNTYFP;
const ACS_TRCT = results.features[i].attributes.TRACTCE;
// push ACS_TRCT, ACS_ST, ACS_TRCT, ACS_CNTY to resulting
// array ctids if they don't present using `.includes` method.
if (!ctids.includes(ACS_TRCT)) ctids.push(ACS_TRCT);
if (!ctids.includes(ACS_ST)) ctids.push(ACS_ST);
if (!ctids.includes(ACS_CNTY)) ctids.push(ACS_CNTY);
if (!ctids.includes(ACS_TRCT)) ctids.push(ACS_TRCT);
}
You can use .find to check if the item is already present in the array ( will only work for primitive types )
var found = ctids.find(function(value) {
return ACS_TRCT === value;
});
if(!found) {
ctids.push(ACS_TRCT);
}

How to loop through all the array of objects?

I have an Array of Object to be used to draw a HTML Table:
Array(5)
0: Object
id: 4
name: Sand Jane
address: Green Sand Street
...
...
...
1: Object
2: Object
...
...
...
I am able to do a single name column defined search with
const temp = this.temp.filter(function (d) {
return d.name.toLowerCase().indexOf(val) !== -1 || !val;
});
temp will contain the filtered data of this.temp
Now I just can't figure out how to loop through all object keys (id,name,address...) so that I can do a global column search in the Table.
UPDATE: I have tried this,
const temp = [];
this.temp.forEach(element => {
for (let key in element) {
if (element.hasOwnProperty(key)) {
let v = element[key];
if (v.toString().toLowerCase().indexOf(val) !== -1 || !val) {
temp.push(element);
}
}
}
});
It works but with performance issues.
RESOLVED: Putting a break after temp.push fixed this issue. Thank you all for the guidelines and references.
temp.forEach(item=>{
for(let key in item) {
//item[key] gives you access to each value
}
})
You can iterate through for loops or even you can usefor loop inside a for loop. Either way it's self explanatory.
var dictionary = {
"employee1":[
{"id":"0","name":"Google"},
{"id":"1","name":"eBay"}
],
"employee2": [
{"id":"2","name":"Yahoo"},
{"id":"3","name":"Facebook"}
]
};
var employee1 = dictionary.employee1;
var employee2 = dictionary.employee2;
for ( var i in employee1) {
var id = employee1[i].id;
var name = employee1[i].name;
console.log(id);
console.log(name);
}
for ( var i in employee2) {
var id = employee2[i].id;
var name = employee2[i].name;
console.log(id);
console.log(name);
}

Accessing dynamic values from JSON object in javascript

this is my json object. i need to get only all the values of packageName and assign it to an array. can any body help me with that. i can not go for using indexes since this is dynamic object.
thanks in advance.
var data = [
{
"packageName":"string",
"packageValue":"string"
},
{
"packageName":"string",
"packageValue":"string"
}
]
Use javascript map function
var packageNames = data.map(function(obj){
return obj.packageName;
})
var data=[
{
"packageName":"string1",
"packageValue":"string"
},
{
"packageName":"string2",
"packageValue":"string"
}
]
var packageNames = data.map(function(obj){
return obj.packageName;
})
console.log(packageNames)
You can use filter function and add to array only when this key exists.
var arr = [];
data.filter(getValue)
function getValue(data){
if(data[packageName]){
arr.push(data[packageName])
}
}
You can add an if statement to check the key and then push it to an array.
for(var i = 0; i< data.length; i++){
for (var property in data[i]) {
if (data[i].hasOwnProperty(property)) {
console.log(property);
console.log(data[i][property]);
}
}
}

Javascript : Select Element in URL with multiple instance of the same element

i need to retrieve a value from an URL in JS, my problem is in this url, the element is repeated at least twice with different value. What i need is the last one.
Example :
http://randomsite.com/index.php?element1=random1&element2=random2&element1=random3
and what i want is "random3" and NOT "random1"
I've tried url.match(/.(\&|\?)element1=(.?)\&/)[2];
But it always gives me the first one :(
I don't have the possibility to change how the url is written as this is for a browser extension.
var ws = "http://randomsite.com/index.php?element1=random1&element2=random2&element1=random3",
input = ws.split("?")[1].split("&"),
dataset = {},
val_to_find = "element1";
for ( var item in input){
var d = input[item].split("=");
if (!dataset[d[0]]){ dataset[d[0]] = new Array(); dataset[d[0]].push(d[1]); }
else{
dataset[d[0]].push(d[1]);
}
}
console.log("item: ", dataset[val_to_find][dataset[val_to_find].length -1]);
return dataset[val_to_find][dataset[val_to_find].length -1];
http://jsfiddle.net/wMuHW/
Take the minimum value (other than -1) from urlString.lastIndexOf("&element1=") and urlString.lastIndexOf("?element1="), then use urlString.substring.
Or alternately, split the string up:
var parts = urlString.split(/[?&]/);
...which will give you:
[
"http://randomsite.com/index.php",
"element1=random1",
"element2=random2",
"element1=random3"
]
...then start looping from the end of the array finding the first entry that starts with element= and grabbing the bit after the = (again with substring).
You could;
for (var result, match, re = /[&?]element1=(.+?)(\&|$)/g; match = re.exec(url);) {
result = match[1];
}
alert(result);
Id try keeping a nested array of duplicate elements
function parseQueryString() {
var elements = {},
query = window.location.search.substring(1),
vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('='),
key = decodeURIComponent(pair[0]),
value = decodeURIComponent(pair[1]);
if (elements.hasOwnProperty(key)) {
elements[key].push(value);
}
else {
elements[key] = [value];
}
}
}
Used on: www.example.com?element1=hello&element2=test&element1=more
Would give you the object:
{
element1: [
"hello",
"more"
],
element2:[
"test"
]
}

Get value from json object without count the array number

This is my json object i want to get alert it without the array order like[0], [1].
var jsononj = {
"objnew" :
[{testarry: "thi is my demo text" },
{testarry2: "thi is my demo text2" }
] };
}
var newtest = jsononj.objnew[0].testarry;
alert(newtest);
i want to alert without [0]. how to i achieve this
I think this is what you're looking for:
var i;
for (i = 0; i < jsonobj.objnew.length; i++) {
if (jsonobj.objnew[i].testarry) {
alert(jsonobj.objnew[i].testarry);
}
}
This is just stupid but I removed the [0]
var jsononj = {
"objnew" : [
{testarry: "thi is my demo text" },
{testarry2: "thi is my demo text2" }
]
};
var a = jsononj.objnew.shift();
alert(a.testarry);
jsononj.objnew.unshift(a);
That's not JSON, that's a Javascript object. JSON is a text format for representing data.
If you want to look for an object with a specific property, loop through the objects in the array and check for it:
var newtest = null;
for (var i = 0; i < jsononj.objnew.length; i++) {
var obj = jsononj.objnew[i];
if (obj.hasOwnProperty('testarry') {
newtest = obj.testarry;
break;
}
}
if (newtest != null) {
// found one
}
doing a var firstOne = jsononj.objnew[0];
but if you simply don't like the [0] through your lines, extend the Array prototype
Array.prototype.first = function () {
return this[0];
};
var newtest = jsononj.objnew.first().testarry;
alert(newtest);
more info at First element in array - jQuery

Categories

Resources