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.
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 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]);
});
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('');
}
i have data in
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London";
i want the result as
Name: John
Employee Id: 2
Salary: $8000
Address: London
is it possible with split() function in javascript?
You can do it with String.split() but in this case it's simpler to use String.replace():
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London";
description = description.replace(/;/g, '\n').replace(/:/g, ': ');
/*
"Name: John
EmployeeID: 2
Salary: $8000
Address: London"
*/
If you want the result as an object, try:
var f = function (str) {
var x = {}, key2label = { EmployeeID: 'Employee Id' };
str.replace(/(.+?):(.+?)(;|$)/g, function (match, key, value) {
key = key2label[key] || key;
x[key] = value;
});
return x;
};
If a simple string is needed, but you still need to replace keys:
var f2 = function (str) {
var key2label = { EmployeeID: 'Employee Id' };
return str.replace(/(.+?):(.+?)(;|$)/g, function (match, key, value, semi) {
key = key2label[key] || key;
return key + ': ' + value + (semi ? '\n' : '');
});
};
If you really didn't mean to replace keys, this will do it:
var f3 = function (str) {
return str.split(':').join(': ').split(';').join('\n');
};
... or use Matt Ball's answer.
With this statement:
var arrDescription = description.split(";");
you will get an array with all the values. For more info on split check the following link.
you can even join them afterwards :
printf(arrDescription.join(" "));
For more info on join check the following link.
Max
You can probable try like this to display.
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London";
var arr=new Array();
arr=description.split(";");
for(var i=0;i<arr.length;i++)
document.writeln("<h4>"+arr[i]+"</h4>");
Yes.
You first should split on the semicolon ;. Loop through those results, and split each result on each colon :.
You will have to build the result by hand.
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London"; var splitted = description.split(";");
for(var i = 0; i < splitted.length; i++) { document.write(splitted[i] + ""); }