How to iterate an object into an array of Object [duplicate] - javascript

This question already has answers here:
Iterate over Object Literal Values
(8 answers)
Closed 2 years ago.
I have create one object and that object I need to pass in one method where I need to iterate by using each object. Since my Obj having only values so it its not getting passed. Can any one help me into this.
My Code :
var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
Now this MyObj I need to pass in one method:
this.someMethod(id, MyObj);
In someMethod i Have one code like
Ext.Array.forEach(MyObj, function (Value) {})
At this point it is getting failed because MyObj is not an array of object. How to correct it.

It would be very helpful if you'd provide more information.
I am not sure what you want to achieve, but there are several ways to iterate through objects.
If you want to split up your object into multiple single-key objects:
> Object.keys(MyObj).map(key => ({ [key]: MyObj[key] }))
[ { country: 'Aus' }, { Time: 'EST' }, { Val: 'Pecific' } ]
On the other hand, if you have a function that takes an array but you want to pass just this one object:
Ext.Array.forEach([MyObj], Value => ())
(But in this case you are better off just calling the function.)

var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
//Without ext
function someMethod(id, MyObj)
{
Object.keys(MyObj).forEach(function (Value) {
console.log(MyObj[Value]);
});
}
someMethod(1, MyObj);
This code (vanilla JS) will get the keys from the Object with Object.keys and allows you to iterate over it. Works for Objects and Arrays.

You can achieve that in the following way:
var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
function someFunction(id, obj){
var objArray = $.map(obj, function(el) {
console.log(el);
return el
});
}
someFunction(1, MyObj)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The ExtJs way
ExtJs provides Ext.Object.eachValue which is what you are searching for.
From the ExtJs documentation:
Iterates through an object and invokes the given callback function for
each iteration. The iteration can be stopped by returning false in the
callback function.
The following code iterrates over each value of MyObj and calls the callback with it.
var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
Ext.Object.eachValue(MyObj, function (Value) {console.log(Value)});

Related

How to make key a variable in firebase updates with React [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 8 years ago.
First off, I'm using Cheerio for some DOM access and parsing with Node.js. Good times.
Heres the situation:
I have a function that I need to create an object. That object uses variables for both its keys and values, and then return that single object. Example:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value');
return { key : value }
})
callback(null, inputs);
}
It outputs this:
[ { key: '1' }, { key: '1' } ]
(.map() returns an array of objects fyi)
I need key to actually be the string from this.attr('name').
Whats the best way to assign a string as a key in Javascript, considering what I'm trying to do?
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
You can't define an object literal with a dynamic key. Do this :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer).

How to set dynamic properties on object in Javascript?

Dynamically I'm getting several objects having the following structure.
obj1 = {
prop: 'one',
key: 'string',
value: 2
}
obj2 = {
prop: 'one',
key: 'diffString',
value: 3
}
Also, I have an object which I want to turn into this using received objects.
mainObject = {
prop: {
key1: value,
key2: value
}
}
I'm trying to use this
mainObject[obj.prop][obj.key] = obj.value;
But it gives me an error because at this point mainObject is just an empty object and it doesn't have mainObject[obj.prop]
Any help will be much appreciated.
The simplest way to achieve this is as follows:
// If no value for obj.prop exists, assign empty object
mainObject[obj.prop] = mainObject[obj.prop] || {};
// Assign value to obj.key of object at mainObject[obj.prop]
mainObject[obj.prop][obj.key] = obj.value;
This code is first ensuring that a valid value (object) exists at the key obj.prop on mainObject. If there is not valid object at key obj.prop, then a new empty object is assigned {}.
The mainObject[obj.prop][obj.key] = obj.value assignment can now be performed safely seeing that an object exists at mainObject[obj.prop].
Alternatively, if you want a more concise way of doing this you could consider the lodash library which offers the .set() method:
_.set(mainObject, obj.prop + '.' + obj.prop, obj.value);
Hope this helps!
all you can do is push your upcoming object into an array and by using reduce method you can simply achieve your desired output
let mainObject = [obj1, obj2].reduce((result, obj) => {
result[obj.prop] = result[obj.prop] || {};
result[obj.prop][obj.key] = obj.value;
return result;
}, {});

Is there a javascript object equivalent to python's pop() on dicts? [duplicate]

This question already has answers here:
Javascript "pop" from object
(8 answers)
Closed 1 year ago.
I'm looking for a JavaScript equivalent of Python's {dict}.pop(). I see that JS has a shift() and pop(), but those are hardcoded for first and last positions in an Array. Is there an equivalent where I can specify the position for an Object?
Example of what I can do in Python:
>>> foxx = {'player':{'name':'Jimmie','last':'Foxx','number':3}, 'date':'2018-01-01', 'homeruns':3,'hits':4}
>>> player = foxx.pop('player')
>>> foxx
{'date': '2018-01-01', 'homeruns': 3, 'hits': 4}
>>> player
{'name': 'Jimmie', 'last': 'Foxx', 'number': 3}
Not in one instruction, but you can get the property and then use delete to remove the property from an object.
let foxx = {'player':{'name':'Jimmie','last':'Foxx','number':3}, 'date':'2018-01-01', 'homeruns':3,'hits':4};
let player = foxx.player;
delete foxx.player;
console.log(foxx);
console.log(player);
So you could create some custom function that does these two operations in one go :
function pop(object, propertyName) {
let temp = object[propertyName];
delete object[propertyName];
return temp;
}
let myObj = { property1 : 'prop1', property2: 'prop2' };
let test = pop(myObj, 'property1');
console.log(myObj);
console.log(test);
There is probably a better way of writing this, suggestions welcome. (for instance, see Martin Adámek's answer for a nice implementation leading to the same python syntax)
I do not think there is such a thing, also note that shift and pop are methods of array, not of an object.
But you could polyfill that yourself easily:
Object.defineProperty(Object.prototype, 'pop', {
enumerable: false,
configurable: true,
writable: false,
value: function (key) {
const ret = this[key];
delete this[key];
return ret;
}
});
var foxx = {'player':{'name':'Jimmie','last':'Foxx','number':3}, 'date':'2018-01-01', 'homeruns':3,'hits':4}
var player = foxx.pop('player')
console.log(foxx, player);
With a custom function:
function pop(obj, key) {
var val = obj[key];
delete obj[key];
return val;
}
The modern way of doing this in js is using the rest operator(3 dots) but still not changing the original object in place.
let obj = {'key1': 'value1', 'key2': 'value2'}
const {key1, ...objNew} = obj;
console.log("key1", key1);
console.log("objNew", objNew);
The above snippet causes the new objNew object to only contain key2 and a new variable key1 will contain the value contained in the key1 property of obj object.
Taken from https://stackoverflow.com/a/53912486/11769765
foxx = {'player':{'name':'Jimmie','last':'Foxx','number':3}, 'date':'2018-01-01', 'homeruns':3,'hits':4}
var {player, ...foxx} = foxx
console.log(foxx)
console.log(player)

Passing an unknown number of nested object properties into a function [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 5 years ago.
Not sure if my title describes what I want to do correctly. Basically, I want a function that extracts properties from objects containing objects. I am going to need to loop through various arrays containing many objects of the same class and extract specific values.
myarray1[
0:
object1 = {
objectProp1: {
objectProp1Prop1:"Hello",
objectProp1Prop2:"Goodbye",
objectProp1Prop3:{
objectProp1Prop3Prop1: "Come here",
objectProp1Prop3Prop2: "Go away"
},
},
objectProp2: "Yo",
objectProp3: "Seeya",
}
1:
object2 = { same as object1 but with other property values }
];
myarray2[
0: { different type of object with a different set of nested properties that the function can extract }
1: { idem }
];
function extractProperty(objectArray, property) {
//How do I write this code?
propertyvalue = objectArray.property;
return propertyvalue;
}
extractProperty(myarray1[0], object.objectProp3) = "Seeya"
extractProperty(myarray1[0], object.objectProp1.objectProp1Prop1) = "Hello"
extractProperty(myarray1[0], object.objectProp1.objectProp1Prop3.objectProp1Prop3Prop1) = "Come here"
In the final code the function needs to be able to loop through all the array keys and create an array list containing the chosen property from every object in the original array, but that I can manage. It's the sending of the specific property that needs to be extracted from the objects in the array into the function that I have no idea how to do.
Is there a generalised way to send a "path" of properties into a function and then use it there? How?
Thanks for your help!
Looks like an assignment to me. So I won't give you the code but will explain the approach.
First you need to pass the property names as a string
In your function you need to split the string based on the delimiter, like .
Keep a reference of current object
Then iterate on all the property names that you got from #2
Fetch current property name from current object and replace current object with the returned value.
return current object at the end.
Note: you need to add some validations in between. I've skipped those for you to explore ;)
You could try recursion:
object1 = {
objectProp1: {
objectProp1Prop1:"Hello",
objectProp1Prop2:"Goodbye",
objectProp1Prop3:{
objectProp1Prop3Prop1: "Come here",
objectProp1Prop3Prop2: "Go away"
},
},
objectProp2: "Yo",
objectProp3: "Seeya",
};
object2 = {
objectProp1: 'test1',
objectProp2: 'test2'
}
var myArray = [object1, object2];
function getProp(objArray, prop) {
for(var key in objArray) {
if (key == prop)
return objArray[key];
if (typeof objArray[key] == 'object')
return getProp(objArray[key], prop);
}
}
//test
document.getElementsByTagName('h1')[0].innerHTML = getProp(myArray[0],'objectProp1Prop3Prop1');
I added a Fiddle for you to try it: https://jsfiddle.net/afabbro/vrVAP/

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);

Categories

Resources