JavaScript- display whole object and specific keys and its value - javascript

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

Related

How to create a json data using two arrays and return it to ajax

key:[id,name,address]
value:[7,John,NewYork]
I wish to create a json data like{"id": 7, "name": "John", "address": "NewYork"} using for(...){...},
and then return it to ajax
$.ajax({
//what kind of format should json data be here?
data:??json data??,
dataType: 'json',
});
Please help me
To the first part of your question:
You could use Array#forEach() and assign all properties with the correspondet value.
var key = ['id', 'name', 'address'],
value = [7, 'John', 'New York'],
object = {};
key.forEach(function (k, i) {
object[k] = value[i];
})
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You could:
iterate through both arrays...
...add the 1st array element to an empty obj as a key...
...and assign the 2nd array element to the 1st array element as it's value.
Each iteration will be paired as key/value when stringified as a JSON.
I'm surprised it actually worked, take a look at the demo below:
SNIPPET
var x = ['id', 'name', 'address'];
var y = [7, 'John', 'NewYork'];
function arrMerge(k, v) {
var obj = {};
for (var i = 0; i < k.length; i++) {
obj[k[i]] = v[i];
}
return obj;
}
var z = arrMerge(x, y);
var json = JSON.stringify(z);
console.log(json);
You can write a general function that zips two arrays together into an object if they're of equal length (also assuming they're in the correct order).
function zip(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
const obj = {};
for (let i = 0; i < arr1.length; i++) {
const key = arr1[i];
obj[key] = arr2[i];
}
return obj;
}
zip(arr1, arr2); // { id: 7, name: "John", address: "NewYork" }
DEMO
You can then use that object as the value of data in your AJAX process.
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string.
jQuery documentation
I guess unlike forEach, since it returns the result, Array.prototype.reduce() comes very handy for these operations. You can even use it at the stage of declaring your JSON data (jData here).
var key = ['id', 'name', 'address'],
value = [7, 'John', 'New York'],
jData = JSON.stringify(key.reduce((p,c,i) => {p[c] = value[i]; return p},{}));
document.write("<pre>" + jData + "</pre>");

Add Dynamic Property To End of Object

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];
}
}
}

Iterating values using Object.Keys

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

Convert an array of object to array of string?

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('');
}

Get the index of an array by position

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.

Categories