I want to print a key: value pair from javascript object. I can have different keys in my array so cannot hardcode it to object[0].key1
var filters = [{"user":"abc"},{"application":"xyz"}];
console.log(Object.keys(filters[0])[0]); // prints user
var term = (Object.keys(filters[0])[0]);
console.log(filters[0].term); // prints undefined
How can i print the value of the key
for (var key in filters[0]){
console.log( key + ": " + filters[0][key]);
}
Or if you want to print all the values of filters
for (var i in filters){
console.log(i);
for (var key in filters[i]){
console.log( key + ": " + filters[i][key]);
}
}
##On #mplungjan 's comment
filters.forEach(function(obj, index){
console.log(index);
for (var key in obj){
console.log(key, obj[key]);
}
});
This is looking for a term property on filters[0]:
console.log(filters[0].term);
What you actually want to do is use the value of term (in your example that will be "user") as the property identifier:
console.log(filters[0][term]);
for loop for array and for..in iteration for object:
var filters = [{ "user": "abc"}, {"application": "xyz"}];
for (var i = 0; i < filters.length; i++) { // the plainest of array loops
var obj = filters[i];
// for..in object iteration will set the key for each pair
// and the value is in obj[key]
for (var key in obj) {
console.log(key, obj[key])
}
}
ES6
[{ "user": "abc"}, {"application": "xyz"}].forEach(
obj => console.log(Object.entries(obj).flat())
)
You can access the value using array syntax
var filters = [{"user":"abc"},{"application":"xyz"}];
console.log(Object.keys(filters[0])[0]); // prints user
var term = (Object.keys(filters[0])[0]);
console.log(filters[0][term]);// prints abc
Lets say that we have a mode object that has some strings in it for example. If we were to do MODE.toString() with just alpha, beta, gamma in the object, what will be returned is [object Object] which is not useful.
Instead, lets say we wanted to get something nice back like Normal, Sepia, Psychedelic. To do that, we could add a toString: function(){...} to our object that will do just that. One catch to this however is that if we loop through everything in the object, the function it self will also be printed, so we need to check for that. In the example I'll check toString specifically, however, other checks like ... && typeof MODE[key] == "string" could be used instead
Following is some example code, calling MODE.toString(); will return Normal, Sepia, Psychedelic
var MODE = {alpha:"Normal", beta:"Sepia", gamma:"Psychedelic",
toString: function() {
var r = "";
for (var key in MODE) {
if (MODE.hasOwnProperty(key) && key != "toString") {
r+= r !== "" ? ", ":"";
r+= MODE[key];
}
}
return r;
}
};
if you want get all keys in array of object, you can try this one mybe
let temp = []
let keys = []
let result = []
for (let i = 0; i < data.length; i++) {
temp = Object.keys(data[i])
for (let j = 0; j < temp.length; j++) {
if(!keys.includes(temp[j])){
keys.push(temp[j])
}
}
temp = []
}
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < keys.length; j++) {
if(data[i][keys[j]] == undefined){
data[i][keys[j]] = ""
}
}
}
return data
or this one if you want take the key from same array 2dimension
function convertObj(arr){
let arrResult = []
for (let i = 1; i < arr.length; i++) {
let obj={}
for (let j = 0; j < arr[0].length; j++) {
obj[arr[0][j]] = arr[i][j]
}
arrResult.push(obj)
}
return arrResult
}
If you want to print key and value, even for nested object then you can try this function:
function printObjectData(obj, n = 0){
let i = 0;
var properties = Object.keys(obj);
let tab = "";
for(i = 0; i < n; i++)
tab += "\t";
for(i = 0; i < properties.length; i++){
if(typeof(obj[properties[i]]) == "object"){
console.log(tab + properties[i] + ":");
printObjectData(obj[properties[i]], n + 1);
}
else
console.log(tab + properties[i] + " : " + obj[properties[i]]);
}
}
printObjectData(filters);
and the solution will look like this:
0:
user : abc
1:
application : xyz
and if you want to remove 0: and 1:
then simply remove
console.log(tab + properties[i] + ":");
after the if statement
Related
I have a loop that has a function inside. my target here is to check if the current data inside the loop are still the same for example my array is like this
var data = ['test1','test1','test1','test2'];
now I will check them if the data on that array inside the loop are currently the same. for example like this.
for (var i = 0; i < data.length; i++) {
var value = data[i][0];
console.log(checkifcurrent(value));
}
my problem here is to return checkifcurrent(value) if it still the same like this
function checkifcurrent(value) {
if (currentvalue is still the same as the last one) {
console.log(same);
} else {
console.log(not same);
}
}
I hope you understand tysm for understanding
You can do it like this, no need for a function call.
var data = ['test1','test1','test1','test2'];
lastValue = data[0];
for (var i = 1; i < data.length; i++) {
var currentValue = data[i];
if(lastValue==currentValue){
console.log("Value is same")
}
else
{
console.log("Value is not same")
}
lastValue = currentValue;
}
you can iterate over the data array and compare with all the array elements except the one at the current position.
If it is equals to the current and the index is not the same of the current then it is a duplicate
var data = ['test1','test1','test1','test2'];
for (var i = 0; i < data.length; i++) {
var value = data[i];
for(var j = 0; j < data.length; j++){
//skip the index at position i, because it is the one we are currently comparing
if(i !== j && data[j] === value) {
console.log('another value like: ' + value + ' at position: ' + i + ' has been found at index: ' + j)
}
}
}
Its not very clear about your task, i hope it is checking if the a value present in arr1 is available are not in arr2. If you so,
Loop through all elements in arr1 and check the indexof it
arr1 =[1,2,3,4];
arr2 = [2,3,4,5,6,6];
arr1.forEach((x)=>{if(arr2.indexOf(x)==-1){console.log('unable to find the element'+x)}})
unable to find the element1
var isSame = (function () {
var previous;
return function(value){
var result = value === previous;
previous = value;
return result;
}
})();
Alternatively you can use lodash difference function to compare old and new array.
http://devdocs.io/lodash~4/index#difference
For example:
const _ = require('lodash')
// Save the old array somewhere
let oldArray = ['test1','test1','test1','test2']
let newArray = ['test1','test1','test1','test3']
const areParametersTheSame = !!(_.difference(oldArray, newArray))
In the following code there is a console log of obj['mn'] which returns the length of that specific object which is 2. The problem with the code is that it doesn't count the multidimentional array, and only it counts the first array. The result should be 4 because there are 4 'mn' in total. What am I doing wrong?
var arr = [['ab','pq','mn','ab','mn','ab'],'mn','mn'];
var obj = { };
for (var i = 0, j = arr.length; i < j; i++) {
if (obj[arr[i]]) {
obj[arr[i]]++;
}
}
console.log(obj['mn']);
This is what you're looking for:
var arr = [['ab','pq','mn','ab','mn','ab'],'mn','mn'];
var obj = { };
function count(arr, obj) {
for (var i = 0, j = arr.length; i < j; i++) {
if (Array.isArray(arr[i])) {
count(arr[i], obj);
}
else if (typeof obj[arr[i]] !== 'undefined') {
obj[arr[i]]++;
}
else {
obj[arr[i]] = 1;
}
}
return obj;
}
console.log(count(arr, obj));
This is a recursive implementation. When it gets to an array, the recursion get one level deeper.
You are calling obj[['ab','pq','mn','ab','mn','ab']], which is obviously not what you wanted.
You need a depth first search.
If arr[i] is an array, then you need to loop through that array.
I'd like to use an object to configure some settings for an app. My idea is to start with this:
var obj = {
property_one: 3;
property_two: 2;
property_three: 1;
}
And I would like to end up with this:
var array = [
'property_one','property_one','property_one',
'property_two','property_two',
'property_three'
]
My current solution is to do this for each property:
function theConstructor(){
for(i=1; i <= obj.property_one; i++){
this.array.push('property_one');
};
for(i=1; i <= obj.property_two; i++){
this.array.push('property_two');
};
for(i=1; i <= obj.property_two; i++){
this.array.push('property_two');
};
}
But this gets tedious, because I might have many properties, and these might change as the app evolves.
I know I can loop through object's properties like this:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
array.push(key);
}
}
But this will push the value to the array, not the key (as a string). Any ideas about how I can do this more efficiently?
Try this
function theConstructor(){
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
for(var i=1; i <= obj[key]; i++){
this.array.push(key);
};
}
}
}
Using Array.prototype.reduce():
var obj = {
property_one: 3,
property_two: 2,
property_three: 1
};
var resultArray = Object.keys(obj).reduce(function(result, curItem) {
for (var index = 0; index < obj[curItem]; index++) {
result.push(curItem);
}
return result;
}, []);
document.write(JSON.stringify(resultArray));
I'm trying to use recursion in JavaScript to deeply go through an object and return its key and value.
An example of this would be:
var json2 = {
'key1': {
'key2Nested': {
'key3Nested': {
'key4Nested': 'SomeValue'
},
'key5Nested': 'unimportantValue',
'key6Nested': 'SimpleValue'
},
'key7Nested': '2SimpleValue',
'key8Nested': 'unimportantValue2'
}
};
The function will take the above input and return something like
['key1/key2Nested/key3Nested/key4Nested', 'SomeValue'],
['key1/key2Nested/key5Nested', 'unimportantValue'],
etc for all values.
The problem is I try to use a for loop on all the object's keys and I try to use recursion inside the loop. But the recursion value returns an array, which ends the for loop.
Here is the code that I have so far:
var makeArray = function(obj) {
var keysArray = Object.keys(obj);
var returnArray = [];
for (var i = 0; i < keysArray.length; i++) {
var key = keysArray[i];
var next_results;
var path, value;
if (typeof(value) != 'object' ) {
value = obj[key];
returnArray = orderedArray.concat([key, value]);
} else if (typeof(value) == "object") {
next_results = makeArray(obj[key]);
if (next_results) {
for (var j = 0; j < next_results.length; j++) {
next_results[j][1] = '/' + key + next_results[j][1];
returnArray = returnArray.concat(next_results[j]);
}
}
}
console.log(returnArray);
return returnArray;
}
}
The function needs to save the key returned from deeper recursion levels so that it can concatenate it to the path.
Perhaps my algorithm can be improved somehow or I'm thinking of it wrong. Can anyone give some advice? Thanks!
Just don't return returnArray inside the for loop body, but only after it.
Also, some other bugs:
The line
next_results[j][1] = '/' + key + next_results[j][1];
doesn't seem to be right. Your keys are in the first slot of each tuple, and you want the slash in between the keys not before them:
next_results[j][0] = key + '/' + next_results[j][0];
In
var path, value;
if (typeof(value) != 'object' ) {
value = obj[key];
you are testing the type of value before assigning it (so that you basically use the value from the previous iteration). Move the property access before the condition!
The method call
returnArray = returnArray.concat(…)
doesn't do what you think it does. You're passing in a tuple (array) that you want to get appended to the array, but the concat method merges the two arrays: [key1, value1].concat([key2, value]) == [key1, value1, key2, value2]. You want to use push instead to get an array of tuples.
In whole:
function makeArray(obj) {
var keys = Object.keys(obj);
var returnArray = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i],
value = obj[key];
if (typeof value != 'object' ) {
returnArray.push([key, value]);
} else {
var next_results = makeArray(value);
for (var j = 0; j < next_results.length; j++) {
next_results[j][0] = key + '/' + next_results[j][0];
returnArray.push(next_results[j]);
}
}
}
return returnArray;
}
I have an array that looks like this:
1. coordinates = [ [16.343345, 35.123523],
2. [14.325423, 34.632723],
3. [15.231512, 35.426914],
4. [16.343345, 35.123523],
5. [15.231512, 32.426914] ]
The latitude on line 5 is the same as on line 3, but they have different longitudes and are therefore not duplicates.
Both the latitude and longitude are the same on line 3 and 6, and are therefore duplicates and one should be removed.
The difficulty in this question that different arrays never compare equal even if they contain same values. Therefore direct comparison methods, like indexOf won't work.
The following pattern might be useful to solve this. Write a function (or use a built-in one) that converts arrays to scalar values and checks if these values are unique in a set.
uniq = function(items, key) {
var set = {};
return items.filter(function(item) {
var k = key ? key.apply(item) : item;
return k in set ? false : set[k] = true;
})
}
where key is a "hash" function that convert items (whatever they are) to comparable scalar values. In your particular example, it seems to be enough just to apply Array.join to arrays:
uniqueCoords = uniq(coordinates, [].join)
You can use standard javascript function splice for this.
for(var i = 0; i < coordinates.length; i++) {
for(var j = i + 1; j < coordinates.length; ) {
if(coordinates[i][0] == coordinates[j][0] && coordinates[i][1] == coordinates[j][1])
// Found the same. Remove it.
coordinates.splice(j, 1);
else
// No match. Go ahead.
j++;
}
}
However, if you have thousands of points it will work slowly, than you need to consider to sort values at first, then remove duplicates in one loop.
I rewrote the answer from thg435 (It does not allow me to post comments) and prototype it also using jQuery instead, so this will work on all browsers using it (Even IE7)
Array.prototype.uniq = function (key) {
var set = {};
return $.grep(this, function (item) {
var k = key
? key.apply(item)
: item;
return k in set
? false
: set[k] = true;
});
}
You can use it like:
arr = arr.uniq([].join);
If you are not on Safari this single liner could do the job
var arr = [[16.343345, 35.123523],
[14.325423, 34.632723],
[15.231512, 35.426914],
[16.343345, 35.123523],
[15.231512, 32.426914]],
lut = {},
red = arr.filter(a => lut[a] ? false : lut[a] = true);
document.write("<pre>" + JSON.stringify(red,null,2) + "</pre>");
It might be simpler to create another array keeping only unique coordinate pairs
var uniqueCoors = [];
var doneCoors = [];
for(var x = 0; x < coordinates.length; x++) {
var coorStr = coordinates[x].toString();
if(doneCoors.indexOf(coorStr) != -1) {
// coordinate already exist, ignore
continue;
}
doneCoors.push(coorStr);
uniqueCoors.push(coordinates[x]);
}
function sortCoordinates(arr){
var obj = {};
for(var i = 0, l = arr.length; i < l; i++){
var el = arr[i];
var lat = el[0];
var lng = el[1];
if(!obj[lat + lng]){
obj[lat + lng] = [lat, lng];
}
}
var out = [];
for(p in obj){
out.push([obj[p][0], obj[p][1]]);
}
return out;
}
I am not sure about coordinates[][] dataType. Make the comparison accordingly.
var dubJRows= new Array();
for(int i = 0; i < coordinates.length -2; i++){
for(int j = i+1; j < coordinates.length -1; j++){
if (i != j && chk_dubJRows_not_contains(j)) {
innerArray1 [1][1] = coordinates[i];
innerArray2 [1][1] = coordinates[j];
if ( innerArray1 [1][0] == innerArray2[1][0]
&& innerArray1[1][1] == innerArray2[1][1]) {
dubJRows.push(j);
}
}
}
}
//REMOVE ALL dubJRows from coordinates.