JS access an array with in an object - javascript

I have a variable holding a string of validated JSON. The JSON is a set of strings each with a value of an array. I'd like to access the string and each array value.
var json_string = {"div-1":["div-1A", "div-1B"], "div-2":["div-2A", "div-2B"]};
//Run some code to get the following result:
console.log("div-1" has "div-1A");
console.log("div-1" has "div-1B");
console.log("div-2" has "div-2A");
console.log("div-2" has "div-2B");
I have tried a bunch of different things but nothing seems to work right. Additionally, I get a weird functionality. If I do the following:
console.log(json_string["div-1"]);
I randomly get the following results for each page refresh :
div-1A //initial load
div-1C //refresh 1
div-1A //refresh 2
div-1B //etc
div-1A //etc
Any ideas how I can get what I am after?

You can first retrieve the values from keys and then use forEach to get their value
var json_string = {"div-1":["div-1A", "div-1B"],
"div-2":["div-2A", "div-2B"]
};
for(var key in json_string){
var _getValue = json_string[key]
if(_getValue.constructor===Array){ // Checking if it is an array
_getValue.forEach(function(item){
document.write('<pre>'+item+'</pre>')
})
}
JSFIDDLE

It'll be something like this if I understand correctly. You have to traverse through each property and take the array property value against that key.
for (key in json_string) {
var arr = json_string[key];
arr.forEach(function(item) {
console.log(key + ' has ' + item);
});
}

Use Object.keys() for getting all object keys and Array#forEach for iterating over array.
var json_string = {
"div-1": ["div-1A", "div-1B"],
"div-2": ["div-2A", "div-2B"]
};
// Get all object keys and iterate over them
Object.keys(json_string).forEach(function(key) {
// Get inner array using key and iterate
json_string[key].forEach(function(el) {
console.log(key + ' has ' + el)
});
});
For older browser check polyfill option for Object.keys method and forEach method.

It looks like your json_string is actually a JSON object (there's a difference). That said, keys within an object do not follow any sort/ordering. You will need to sort your keys before your output:
var obj = {
"div-1": ["div-1A", "div-1B"],
"div-2": ["div-2A", "div-2B"]
};
Object.keys( obj ).sort().forEach( key =>
obj[ key ].sort().forEach( val =>
console.log( [key,'has',val].join(' ') )
)
);
Of course you could also write your own function to output values for a specific key. Below adds a prototype function to Object, which is just an example (prototyping is generally not recommended):
Object.prototype.valuesFor = function(key){
this[key].sort().forEach( val =>
console.log( [key,'has',val].join(' ') )
)
return this[key];
};
var obj = {
"div-1": ["div-1A", "div-1B"],
"div-2": ["div-2A", "div-2B"]
};
obj.valuesFor('div-1')

Related

how to insert new object in node js array if key not exist

I want to create data structure like that.
Var ans =[{"b":[1,2]},{"g":[100,2]}]
I want to create a new object within list if key not exists in list ans.
Else if key exists in one object of ans list then I want to add new values into the object of ans list
For Example:
Example 1) new data c:{2000}
then
Var ans =[{"b":[1,2]},{"g":[100,2]},{c:[2000]}]
Example 2) new data g:{50}
then
Var ans =[{"b":[1,2]},{"g":[100,2,500]},{c:[2000]}]
I am a beginner in node js, understand array, object concept, but not getting exact logic!
Thanks!
You can try following:
Logic
Filter array based on key
Check if object with mentioned key exists or not.
If yes, push value to this array.
If not, create a dummy object and push this object to original array.
Correction, when you do .push({key: value}), key will be considered as string.
Alternates
If you are using ES6, .push({ [key] : value })
Create a dummy object var o = {}. Set key and value to it o[key] = value and push this object.
Optimisations
Instead of setting value like obj[key] = value, since we will be operating on arrays, try obj[key] = [].concat(value). This will enable you to pass value as number or array of values.
Instead of checking the existence of value in .filter, try Array.isArray to check if value exists and is of type array.
Custom function
function checkAndPush(array, key, value) {
var filteredList = array.filter(function(o) {
return Array.isArray(o[key]);
});
filteredList.length > 0 ? filteredList[0][key].push(value) : array.push({
[key]: [].concat(value)
});
return array;
}
var ans =[{"b":[1,2]},{"g":[100,2]}]
console.log(checkAndPush(ans, "c", [2,3]))
console.log(checkAndPush(ans, "c", 4));
Prototype function
Array.prototype.checkAndPush = function(key, value) {
var filteredList = this.filter(function(o) {
return Array.isArray(o[key]);
});
var dummy = {}
dummy[key] = [].concat(value)
filteredList.length > 0 ? filteredList[0][key].push(value) : this.push(dummy);
// or ES6: this.push({ [key]: [].concat(value) })
return this;
}
var ans =[{"b":[1,2]},{"g":[100,2]}]
console.log(ans.checkAndPush("c", [2,3]))
console.log(ans.checkAndPush("c", 4));
If you are dealing with objects as your values
ans[key] = ans[key] || []
ans[key].push(value)
Note, this works because your values will be an array. If they could be primatives then you would use hasOwnProperty to check.
if (ans.hasOwnProperty(key)) {
// Add this to your key somehow
} else {
// initialize the key with your value
}
Node.js is nothing but a library built on javascript. You can do anything using javascript type of progmming. However push and pop method should be able to help you to deal with nodejs array.
ans[key].push(value)

Find index of object in array by key

I have an array of objects like so
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
I'm trying to modify one, but I only know its key. I need to pinpoint the item1 object so I can change its value (the values are random and I don't know them, so I can't rely upon them).
If I could just get the index of the item it would be pretty easy: myobj[index].value = "newvalue".
Maybe using the index isn't the best way, so if it isn't, I'm open to other ideas.
I was thinking I could try something like
myobj.objectVar
Where objectVar is the key I'm being passed (item1, for example), however this does not work, possibly because it's a variable? Is it possible to use a variable like this maybe?
If it helps, I'm using underscore.js as well.
Your guess at a solution doesn't work because you're not accessing the individual objects, you're accessing an array of objects, each of which has a single property.
To use the data in the format you've got now, you need to iterate over the outer array until you find the object that contains the key you're after, and then modify its value.
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
function setByKey(key, value) {
myObj.forEach(function (obj) {
// only works if your object's values are truthy
if (obj[key]) {
obj[key] = value;
}
});
}
setByKey('item1', 'new value');
Of course, the far better solution is to stop using an array of single-property objects, and just use one object with multiple properties:
myobj= {"item1" : info in here, "item2" : info in here, "item3" : info in here};
Now, you can simply use myObject.item1 = "some new value" and it will work fine.
You can write a function like,
function getElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
// if the key is present, store the object having the key
// into the array (many objects may have same key in it)
objectsHavingGivenKey.push(individualObject);
}
});
// return the array containing the objects having the keys
return objectsHavingGivenKey;
}
If you only want to get the index of elements having the given key
You can do something like this,
function getIndexesOfElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject, index) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
//push index of element which has the key
objectsHavingGivenKey.push(index);
}
});
// returns the array of element indexes which has the key
return objectsHavingGivenKey;
}
Try this code:
function changeObj( obj, key, newval )
{
for( var i=0, l=obj.length; i<j; i++)
{
if( key in obj[i] )
{
obj[i] = newval;
return;
}
}
}
var myObjArray= [{"item1" : "info in here"},{"item2" : "info in here"}, {"item3" : "info in here"}]
To find and add new value to the object inside an array:
myObjArray.forEach(function(obj) {
for(var key in obj) {
// in case you're matching key & value
if(key === "item1") {
obj[key] = "update value";
// you can even set new property as well
obj.newkey = "New value";
}
}
});
You can access objects the same using their index, even the object inside the original object.
Is this kind of what your looking for:
var otherObj = [{"oitem":"oValue"}];
var myobj= [{"item1" : otherObj},{"item2" : "2"}, {"item3" : "tesT"}];
myobj[0].item1[0].oitem = "newvalue";
alert(myobj[0].item1[0].oitem);

Append objects in local storage

I store objects in local storage with the following:
localStorage.setItem('obj', JSON.stringify(obj));
I want to add multiple instances of obj every one second, giving a time key. How can I append obj instead of change it every time?
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem =
{
'product-name': itemContainer.find('h2.product-name a').text(),
'product-image': itemContainer.find('div.product-image img').attr('src'),
'product-price': itemContainer.find('span.product-price').text()
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
You may also want to consider using an object instead of an array and use the product name as the key. This will prevent duplicate entries showing up in LocalStorage.
Basically you have to retrieve the object, add your value and then write it back to localStorage.
var obj = JSON.parse( localStorage.getItem('obj') ) || {};
obj[ timestamp ] = 'newvalue';
localStorage.setItem('obj', JSON.stringify(obj));
There are two options:
Instead of storing the object store a list/map of objects, then to add an element just first do the getItem, then push/set the new element, then use setItem.
Store the objects using the date as the key (e.g. localStorage.setItem('obj:' + x.time, x)) and the use for (x in localStorage) {...} to find all the keys.
function store()
{
var person=new Object();
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
localStorage.setObj("temp", person);
var obj=localStorage.getObj("temp");
for(var i in obj)
alert(i+"--"+obj[i]);
}
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
}

Object, Array and $.each()

I thought I solved my problem using the for (var key in arr) suggested here but this causes trouble in IE. Now I am back to square one.
var myVariable = [];
myVariable['option-1'] = 'something';
myVariable['option-2'] = 'something else';
$.each(myVariable, function(index, value) {
alert(index + ': ' + value);
});
It doesn't work. Nothing shows. Can someone edit it to make it work?
Just use an object instead of an array:
var myVariable = {};
Change var myVariable = []; to var myVariable = {};.
The syntax that you're using, myVariable['option-1'] = 'something'; is for objects, not arrays.
myVariable is an array. To add things to an array you use myVariable.push('something'). You are using square bracket syntax, which is how you would normally add properties to an object.
Since arrays are objects, you can still access option-1, but it is not a member of the array, it is a property of the object: myVariable['option-1']; // "something"
The solution is to set myVariable to an object. jQuery's each method will iterate over the properties of the object as expected.
No need for jQuery.
Just use a for..in loop (with an object {} not an array []):
for(var index in myVariable) {
var value = myVariable[index];
alert(index + ': ' + value);
}
There are no associative arrays in JavaScript, and non-numeric properties on arrays are bad practise!.
Instead, use an object literal:
var myVariable = {};
// ^^
myVariable['option-1'] = 'something';
…

What javascript techniques are used in this array parser?

I have the following script that dumps a given array's contents
function dump(obj) {
obj = obj || {};
var result = [];
$.each(obj, function (key, value) { result.push('"' + key + '":"' + value + '"'); });
return '{' + result.join(',') + '}';
}
... but I don't understand the "array" functions of this. Can you tell me what I need to learn to comprehend what is going within the .each statement?
Update
e.values below is an example of what obj looks like.
This is using jQuery for the each http://api.jquery.com/jQuery.each/ to do the iterating. Here is what happens in your dump function:
function dump(obj) {
// If 'obj' is falsy then make 'obj' a new Object
obj = obj || {};
// Create a new Array
var result = [];
// Loop over each property in 'obj' and add
// "key":"val" String to the 'result' Array,
$.each(obj, function (key, value) { result.push('"' + key + '":"' + value + '"'); });
// Join the Array using "," as the delimiter and wrap
// this with { ... }. Example of arr.join():
// var arr = [1, 2, 3];
// console.log(arr.join(".")); // "1.2.3"
// console.log(arr.join("|")); // "1|2|3"
return '{' + result.join(',') + '}';
}
Edit
If you need to get the key(s) of an arbitrary Object you can use:
function getKeys(obj) {
var keys = [],
i;
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push(i);
}
}
return keys;
}
var keys = getKeys({key: "value"}); // ["key"]
Here's a working example.
You could also have a look at Underscore.js's _.keys().
Basically all that code is doing is creating a string version of the object.
Demo: http://jsfiddle.net/GYJAT/
The $.each is a jQuery function that goes through the array.
Based on the comments you left, it seems that your main question is about how to get the keys of an object.
First, in your code sample jQuery does it automatically for you as part of the each function:
$.each(obj, function (key, value) ...
If you need to do it yourself, modern browsers have the keys property: Object.keys(obj)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys
With older browsers, you'll need to use a for loop (note the HasOwnProperty test):
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/HasOwnProperty#Example:_Iterating_over_the_properties_of_an_object

Categories

Resources