I am trying to iterate through vales of properties of an object.
here is my code
var player =
{
name: 'kaka',
age: 33,
address: '22 green street',
sayHello: function () {
console.log('my name is ' + this.name + "my age is " + this.age);
}
}
var myProperties = Object.keys(player);
for (var i = 0; i < myProperties.length; i++) {
console.log(myProperties[i]);
}
But it only displays the properties and not values.
How can i go through values like 'kaka' for name..
Thanks.
You would need to use the keys as lookup in original object
for (var i = 0; i < myProperties.length; i++) {
if(typeof player[myProperties[i]] !== 'function'){
console.log(player[myProperties[i]]);
}
}
In the end I'm not sure you gain much creating and iterating the keys vs using a for in loop for this use case
Note that since Object.keys returns an Array, you can use an iterator like forEach for convenience:
Object.keys(player).forEach(function(key) {
console.log(key + ': ' + player[key]);
});
Related
I am using this code
var obj = { 'name':'Some Person Name',
'country':'Country of Some Person',
'age':1
}
var storeVal = Object.keys(obj)
for (var i = 0; i < storeVal.length; i++) {
var storeLoop = storeVal[i] ;
document.write('<pre>'+storeLoop+'</pre>');
}
Now I can display the keys of object obj using above code and I also know how to display values of object obj using Object.values(). I want to know how I can display the whole object obj using above for loop and I am not talking about for..in loop. I want to also know how to display the specific key and value,for example if I want to display only name key and its value,how that can be done ? I am only using JavaScript. No jquery.
Here's one way to do it:
var obj = { 'name':'Some Person Name',
'country':'Country of Some Person',
'age':1
}
var storeVal = Object.keys(obj)
for (var i = 0; i < storeVal.length; i++) {
var storeLoop = storeVal[i] + ': ' + obj[storeVal[i]];
document.write('<pre>'+storeLoop+'</pre>');
}
// Just displaying a certain key:
document.write('<pre>Name: '+obj.name+'</pre>');
I suggest to use variable names which reflects their content, then I suggest to declare all variables first, an not for example inside of a for loop.
For getting the value of a property of an object, you could use one of two syntax as property accessor
object.property // dot notation
object['property'] // bracket notation
To get a value of the object, you could use
object.name // 'Some Person Name'
var object = { name: 'Some Person Name', country: 'Country of Some Person', age: 1 },
keys = Object.keys(object),
value,
i,
nameKey = 'name';
for (i = 0; i < keys.length; i++) {
value = object[keys[i]];
document.write('<pre>' + keys[i] + ': ' + value + '</pre>');
}
document.write('<hr><pre>' + nameKey + ': ' + object[nameKey] + '</pre>');
If it is just for you and you don't really want to output it in the HTML code, you can use console.log(storeVal); and explore the printed object in your browser console.
See more here: https://developer.mozilla.org/en-US/docs/Web/API/Console/log
Use Object.entries() , see MDN-Doc
Basic example:
var obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
Your code:
var obj = { 'name':'Some Person Name',
'country':'Country of Some Person',
'age':1
}
Object.entries(obj).forEach(([key, value]) => {
// Do whatever you like with key and value
});
I am creating an object and set its properties dynamically and push it to an array, as below:
var modelData = [];
var data = {}
data['rain'] = '123';
var items = [{name: 'prod', default_id: 1}, {name: 'dev', default_id: 2}]
for (var i = 0; i < items.length; i++) {
var id = items[i].name;
data[id] = items[i].default_id;
}
modelData.push(data)
This works fine but by default it adds the properties in ascending order. I want it to be added to the end of the object, so my properties would be rain, prod, dev instead of dev, prod, rain
Is that possible?
see this jsfiddle console for an example.
Objects don't have a guaranteed order in JS. The closest thing you can get is an array of arrays:
var ordered_object = [];
ordered_object.push(['rain', 'First element']);
ordered_object.push(['prod', 'Second element']);
ordered_object.push(['dev', 'Third element']);
ordered_object.forEach(function(pair) {
var key = pair[0],
value = pair[1];
console.log(key + ': ' + value);
});
It will be ordered, but getting the value of a "property" (they're not really properties any more) is a little more difficult:
function get_value(ordered_object, key) {
for (var i = 0; i < ordered_object.length; i++) {
if (ordered_object[i][0] === key) {
return ordered_object[i][1];
}
}
}
I'm having an array of object like this-
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23},
{name: 'Richa', age:25, adddress:'ABX', email:'abc#xyz.co'}
];
now i want output like this
var string_person = [{sparsh22XYZ},{ankur23},{Richa25ABXabc#xyz.co}];
is their any way to get output like this in javascript, jquery, Angular.js.
Any other web used language is approved.
Check out this jsfiddle. You'll see both Array.prototype.reduce and Array.prototype.map used, both with the same results.
This is classic reduce:
var people = person.reduce(function(agg, p) {
return agg.concat([p.name + p.age + p.address]);
}, []);
The above uses Array.prototype.reduce.
In other words, when you want all the properties of an object or array "reduced" into something, then the most semantic go-to option is probably Array.prototype.reduce in this case.
However, Array.prototype.map can also do the job quite cleanly:
var people = person.map(function(p) {
return p.name + p.age + p.address;
});
This is an argument, now, between readability/complexity vs. semantics.
To limit incidental complexity (in the form of readability), I might go for the map function, even though you could argue this is technically a paradigmatic reduction.
Try this, this method suitable for different object names, it will work good.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23},
{name: 'Richa', age:25, adddress:'ABX', email:'abc#xyz.co'}
];
var result = person.map(function(p){ return Object.keys(p).map(function(k){return p[k]}).join("");})
You can do it like this.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23, address:'ABC'}
];
var test = person.map(function(one){
var properties = Object.getOwnPropertyNames(one);
return properties.map(function(prop){
return one[prop];
}).join('');
});
console.log(test);
I think it will help you.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23, address:'ABC'}
];
var stringarray=[];
// $.each(person, function (i, d) {
// stringarray.push(d.name + d.age + d.address);
// });
//for(var i = 0; i < person.length; i++){
// stringarray.push(person[i].name + person[i].age + person[i].address);
//}
var stringarray = person.map(function(p) {
return p.name + p.age + p.address;
});
console.log(stringarray);
Result: ["saprsh22XYZ", "Ankur23ABC"]
Plz Try this one.
I assume you want a array of strings.
[{sparsh22XYZ},{ankur23ABC}]
is not such an array.
If you want
[ "sparsh22XYZ", "ankur23ABC" ]
you can simply go with
Plain old Javascript:
var string_person = [];
for (var i = 0; i < person.length; i++) {
string_person.push(person[i].name+person[i].age+person[i].address);
}
Underscore.js library
If all you need is a list of values of one of the object properties, it's easiest to go with underscore.js library.
var string_person = _.pluck(person, 'name');
http://underscorejs.org/#pluck
Call the below function on any array of Objects with any number of parameters, it will return you what you want.
function getStringArray(array){
var resultArray = [];
for (i = 0; i < array.length; i++) {
var result = "";
var keysArray = Object.keys(array[i]).sort()
for(j = 0; j < keysArray.length; j++){
result = result+array[i][keysArray[j]];
}
resultArray.push(result);
}
return resultArray;
}
var string_person = [];
for(var i = 0; i < person.length; i++){
string_person.push(person[i].name + person[i].age + person[i].address);
}
Updated:
Also You can use Underscore:
var string_person = _.map(person, function(p){return p.name + p.age + p.address;});
I guess you want to join all members of the object to a string. There are two ways to do this:
// iterate through the array of persons
for (var index = 0; index < person.length; index++) {
var obj = person[index]; // save the object temporally
person[index] = ''; // place an empty string at the index of the object
// iterate through all members of the object using the "in"-operator
for (var member in obj) {
person[index] += obj[member]; // add the value of the member to the string
}
}
The problem with this technique is, I cannot guarantee that it will join the values of the members in the order you want. It should join them in the order in which the members were defined.
Anyway this solution works fine but only in your case:
// iterate through the array of persons
for (var index = 0; index < person.length; index++) {
// place a string which contains the joined values of the members in the right order at the index of the object
person[index] = [
person[index].name,
person[index].age,
person[index].address
].join('');
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamic object property name
I want to dynamically generate access to an object's property.
If I try to access mydata[i].val.name I get somename.
If I try it like mydata[i] + bar[j] (where bar[j] === '.val.name') it fails.
How do I dynamically create something like this? So that I can access any property of an object using a user generated value?
Some code:
If I have an object I want to be able to iterate through its properties, gathering the ones I am interested in. Ideally I would like something like the following:
var processData = function (data, keys, values) {
var returnData = [], i, j, k;
var parsedData = JSON.parse(data);
var keys = keys || null;
var values = values || null;
var datalen = parsedData.length;
for (i = 0; i < datalen; i++) {
returnData[i] = {};
for(j = 0; j< keys.length; j++){
for(k = 0; k < values.length; k++){
returnData[i][keys[j]] = parsedData[i] + values;
}
}
}
return returnData;
};
and then use it like:
var keys = ["foo","bar"];
var values = [".val.name", ".val.date"];
processData(data, keys, values);
But this does not work and in console I see foo="[object Object].val.name" rather than the expected foo="ACME Industries".
If you want to stick to your pattern of constructing the subscript as a string with dots in it you have to roll your own lookup function, like so:
function descend(object, sub) {
var handle = object,
stack = sub.split('.'),
history = [],
peek;
while (handle[stack[0]]) {
if (peek) {
history.push(peek);
}
peek = stack.shift();
handle = handle[peek];
}
if (stack.length > 0) {
history.push(peek);
throw "Traversal error, could not descend to '" + stack.join('.') + "' from '" + history.join('.') + "'.";
}
return handle;
}
var x = {
a: {
b: {
c: 15
},
d: 4
}
};
console.log(descend(x, "a"));
console.log(descend(x, "a.b"));
console.log(descend(x, "a.b.c"));
console.log(descend(x, "a.d"));
function processData(data, keys, values) {
if (keys.length !== values.length) {
throw "Mismatched keys and value lookups";
}
var i,
len = keys.length,
gathered = {},
k,
scratch,
v;
for (i = 0; i < len; i += 1) {
k = descend(data, keys[i]);
scratch = values[i].split('.');
scratch.shift();
v = descend(k, scratch.join('.'));
gathered[keys[i]] = v;
}
return gathered;
}
var data = {
foo: {
val: {
name: "ACME Industries"
}
},
bar: {
val: {
date: (new Date())
}
}
};
var keys = ["foo","bar"];
var values = [".val.name", ".val.date"];
processData(data, keys, values);
Please note: this will not be nearly as performant as coding without this style of lookup.
If you try:
new Object() + '.john.doe'
It will concatenate as a string, so you’ll get "[object Object].john.doe".
You should create a function that can handle dynamic property names instead (and there are plenty of those). You also might want to loose the ".foo.bar" syntax as a string (unless you plan to use eval()) and work solely with arrays instead.
If I understand correctly you need to use
mydata[i]["val"]["name"]
So, I'd use something like this:
var result =getItemByValuesPath(myData[i],values);
alert(result);
function getItemByValuesPath(item, values)
{
var result = item;
var vals = values.split(".");
for(var j=0; j<values.length; j++)
{
if(result==undefined)
{
return null;
}
result = result[values[j]];
}
}
I want to get the index of an array by position. Is this possible? For example, I want the following function to print:
var args = new Array();
args["name"] = "john";
args["surname"] = "smith";
printPerson(args);
function printPerson(args) {
for(var i = 0; i < args.count; i++) {
???
}
}
"name:john surname:smith"
(ie name & surname should not be hardcoded inside function)
EDIT
The order they printed out is not important!
You are assigning properties to an Array, and want those properties to appear in some order?
No need for an Array. Better use an Object literal:
var person = {
name:'John',
surname:'smith',
toString: function(){
return 'name: '+this.name
+', surname: '+this.surname;
}
};
alert(person); //=>name: john, surname: smith
Not tested:
for(var i in args)
alert(i + ":" + args[i]);
EDIT:
If order matters, you could make an array of objects.. Like
args[0] = { key: 'name', value: 'john' };
args[1] = { key: 'name', value: 'mike' };
for(var i = 0; i < args.length; i++)
alert(args[i].key + ":" + args[i].value);
Or something..
These values are simply properties of the args object. So you can iterate over them by using for...in
var args = new Array();
args["name"] = "john";
args["surname"] = "smith";
for(x in args)
document.write(x + ":" + args[x] + " ");
<html>
<body>
<script type="text/javascript">
var args = new Array();
args["name"] = "john";
args["surname"] = "smith";
function printPerson(args) {
for(key in args) {
alert(key + ":" + args[key]); // you can write your values, rather than alert them, but gives you the idea!
}
}
printPerson(args);
</script>
</body>
</html>
This isn't the correct use of Array in JavaScript, which should only use a numeric index. By adding string-key properties, you are adding instance properties but they aren't enumerable in a for loop. You can use an Object instead, which is a set of key/value pairs.
KooiInc's answer demonstrates the use of Object for this purpose.
I think you can use for .. in for this. There's an example on that page.