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));
Related
I have an object something below in the code. but while iterating over the object i get only the last value. I cannot understand what i am doing wrong here !
var index = {};
var demoObj = [{
0:{obj1: {...}, obj2: {...}, obj3: {...}}
},
{
1:{obj1: {...}, obj2: {...}, obj3: {...}}
}];
for (var i = 1; i <= demoObj.length; ++i) {
index[i] = demoObj[i] ;
}
console.log(index);
Seems like you are skipping index 0
for (var i = 1; i <= demoObj.length; ++i) {
change to this
for (var i = 0; i <= demoObj.length; ++i) {
You are logging your value after the for loop is done, try logging it inside the for loop.
And also variables are lowercase ;)
for (var i = 1; i <= demoObj.length; ++i) {
index[ i ] = demoObj[i] ;
console.log(Index);
}
I am trying to get all leaf value of any kind object as array.
Here is sample object and I want to get [1, 2, 3] from this object.
{
“group1”:[
{
“value1”:”1”,
"value2”:”2”
},
{
“gropu2”:[{
"gropu3”:”3”
}]
}]
}
Here is current implementation.
var t = {
"a":[
{
"a":"1",
"b":"2"
},
{
"d":[{
"e":"3"
}]
}]
}
function getNode( node ){
if(node == null)
return null;
if(typeof node !== 'object'){
return [node];
}
var arr = [];
for( var i = 0; i < node.length ; i ++){
Array.prototype.push.apply(arr, getNode(node[i]));
}
return arr;
}
$(document).ready(function(){
console.log(getNode(t));
});
But it is showing nothing.
I can’t understand where I am doing wrong with my implementation and is there any other easy way to get this done?
The problem is in this line.
for( var i = 0; i < node.length ; i ++){
Here you can not access all element of object using for loop.
You have to convert object to array and then do that.
var array_node = Object.keys(node).map(function(key) { return node[key] });
for( var i = 0; i < array_node.length ; i ++){
Array.prototype.push.apply(arr, getNode(array_node[i]));
}
FIDDLE
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 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
I have the below javascript array with me
var test =[{
Maths:{
ST1:10,
ST2:2,
ST3:15}
},
{
Science:{
ST1:50,
ST3:40}
}
]
I want to generate the array shown below out of this
var t = [{ST1:{
Maths:10,
Science:50
},
ST2:{
Maths:2,
Science:0
},
ST3:{
Maths:15,
Science:40
}
}]
I tried using the code shown below
for (var key in test) {
if (test.hasOwnProperty(key)) {
for (var key1 in test[key]){
//console.log(key1)}
var abc = test[key][key1];
for(var x in abc)
{
console.log(x+key1+abc[x])
}
}
}
}
I am new to this help me doing this.
This does mostly what you want...
var t = {};
for (var i = 0; i < test.length; i++) {
for (var name in test[i]) {
for (var level in test[i][name]) {
if (!t[level])
t[level] = {}
t[level][name] = test[i][name][level]
}
}
}
Only thing missing is to get the Science:0 for when a STx value is missing under a section.
DEMO: http://jsfiddle.net/eHwBC/
Result:
{
"ST1": {
"Maths": 10,
"Science": 50
},
"ST2": {
"Maths": 2
},
"ST3": {
"Maths": 15,
"Science": 40
}
}
Keep in mind that there's no guaranteed order when using for-in for enumeration.
If the labels (Math, Science, etc) are known in advance, then you can ensure that each object gets all labels.
If not, a separate loop can be done. Depending on the approach, it could be done before or after this main loop.
Do you know about JSON.stringify(t)?
It will convert an object literal to JSON.
Mozilla's documentation of this function is available at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify.
You can also read this blog article for further explanation
Try this:
var test =[{
Maths:{
ST1:10,
ST2:2,
ST3:15
}
},
{
Science:{
ST1:50,
ST3:40}
}
];
var result = [];
for(i = 0; i <= test.length; i++){
var resultRow = {};
for(key in test[i]){
for(subKey in test[i][key]){
if(resultRow[subKey] == undefined){
resultRow[subKey] = {};
}
resultRow[subKey][key] = test[i][key][subKey];
}
}
result.push(resultRow);
}
Try like below,
/* Iterator start */
var t = {};
for (var i = 0; i < test.length; i++) { //Iterate Maths, Science,..
for (var key in test[i]) { //Iterate Math
for (var iKey in test[i][key]) { //Iterate ST1, ST2, ST3
var s = (t.hasOwnProperty(iKey))?t[iKey]:createObject();
s[key] = test[i][key][iKey];
t[iKey] = s;
}
}
}
/* Iterator End */
p = [];
p.push(t);
//^- p is what you want
// Separate function so you can add more items later without changing logic
function createObject () {
return {'Maths' : 0, 'Science': 0};
}
DEMO and Proof below,