Javascript array inside array - javascript

I am creating an array like this:
var groupUserCounter=[];
groupUserCounter["asd"]=1;
groupUserCounter["asd2"]=2;
var groupC=[];
for(var key in groupUserCounter) {
groupC.push(key);
}
console.log(groupC);
Output:
Array [ "asd", "asd2" ]
But I need something like this:
Array [ ["asd"], ["asd2"] ]
How can I achive this?

When you push your key into groupC, you have to push a key array, not just the value.
var groupUserCounter=[];
groupUserCounter["asd"]=1;
groupUserCounter["asd2"]=2;
var groupC=[];
for(var key in groupUserCounter) {
groupC.push([key]);
}
console.log(groupC);
EDIT
A more elegant way is using .keys() and .map() method.
var groupUserCounter=[];
groupUserCounter["asd"]=1;
groupUserCounter["asd2"]=2;
var groupC = Object.keys(groupUserCounter).map(function(elm){
return [elm]
});
console.log(groupC);

$.makeArray() functions returns any object into a native Array.just like below
$.each(groupUserCounter, function(index, value) {
groupC.push($.makeArray( value));
});
console.log(groupC);//something like this what u expected Array [ ["asd"], ["asd2"] ]

Related

Pushing a value to an array of objects

I can't seem to figure out as to why I am unable to append a value to my array below? Is there a special syntax to follow or something when constructing an array like in the method used below?
var arr = {
"fruits": ['apple','banana','orange']
};
arr.push({ "fruits":"testing123"}); // This line fails
alert(arr["fruits"]);
Try: arr.fruits.push("mango");
You can't push() to an object. You should either use the key-value notation:
arr.anotherFruits = "testing123"; // another key
arr.fruits = "testing123"; //to overwrite
Or make arr actually array:
var arr = [
{"fruits": ['apple','banana','orange']}
]
arr.push({ "fruits":"testing123"})
alert(arr["fruits"])
In this case you'd get
var arr = [
{"fruits": ['apple','banana','orange']},
{"fruits":"testing123"}
]
Or in case you did want to get an object like this
var arr = {
"fruits": ['apple','banana','orange','testing123']
}
you should've used arr.fruits.push('testing123');
Your array defintion is all wrong. Assuming you want arr to be an object that has an array under fruits and then push another value inside fruits, use the following:
var arr = {
fruits: ['apple', 'banana', 'orange']
};
arr.fruits.push("testing123");
console.log(arr["fruits"]);
Change your initial arr declaration to this...
var arr = [{
"fruits": ['apple','banana','orange']
}];
Then you can push more objects onto it. E.g.
arr.push({"fruits": ['mango', 'pear', 'tomato']});
Or, if you wish to push fruits to the existing array INSIDE your object, then simply use your existing arr declaration and use it like this...
arr.fruits.push('tomato');
arr.fruits.push('pear');
arr.fruits.push('tomato');
I'd argue that you don't really require this to be an object at all here.
All you need is this...
var fruits = [];
fruits.push('banana');
fruits.push('apple');
It's simply an array of fruits. If you need more complex structure, then use an array of objects, instead of strings.
Array has push() method, but Object does not. Here you create an Object, but not an Array. So it failed.

Convert Object array to String Array

I have an Object array that looks like the following:
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
And I want to convert it to look like this:
var newArray = [
1, 2, 3
]
So it's basically taking the object array, extracting the id's out of the objects, and creating a new array that contains the id's that were extracted. Is there a way to do this in one line? Even better if a new array doesn't have to get created and array is just updated.
var test ="sai";
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
console.log(array.map(function(obj){return obj.id}))
iterate the array using foreach and populate newArray
var newArray = [];
array.forEach(funtion(element){
newArray.push(element.id);
});
console.log( newArray );
array.map(function (item) {
return item["id"];
}
If you'd like to have anew instance of the mapped array:
var newarray = [];
array.forEach(function (item) {
newarray.push(item["id"]);
}
array.map(function(element) {return element.id})
OP Requirement: better if array is just updated
array = array.map(function(element) {return element.id})

Underscore: How to return all values by array with keys

I have big object with a lot of key : value, and I have array with some keys from this object.
How to return values of this keys(array) by underscore?
I try some like this, but it's bull**
_.find(objectwithkeysandvalues , function(value){
return _.intersection(value,arraywithekeys)
});
You don't need Underscore for this task. Instead, you can use the map function to create a new array that contains the values specified by the keys in the old array:
var myValues = keys.map(function (key) {
return myObject[key]
});
You only need to map each value from your keys array to yourBigObject[value].
In Underscore this would look like this :
var keys = [ ... ]; // Keys from your big object
var obj = { ... }; // Your big object
var values = _.map(keys, function(value, index) {
return obj[value];
});
See this fiddle for experimenting.
Here's a solution using upcoming EcmaScript 7 Array Comprehensions available today via Babel.js.
Try it: Array Comprehensions Example.
ES7:
var obj = {
"key1": 1,
"key2": 2,
"key3": 3
}
var arr = ["key1"];
var values = [for(key of arr) obj[key]];
console.log(values);

Iterate through a json object

Here is my object
var myObject = {"HardGood":362,"Music":2};
console.log(myObject[0]); // undefined? instead of "Hardwood 362"
What am I doing wrong?
myObject is an object not an array, so using [0] will indeed be undefined.
Use myObject.HardGood or myObject.Music to get the value or that property
Code
console.log(myObject.HardGood); // will output 362
console.log(myObject.Music); // will output 2
UPDATE
var objects = [
{
"title": "HardGood"
"type": "362"
},
{
"title": "Music"
"type": "2"
}
];
console.log(objects[0].title); // output HardGood
console.log(objects[1].type); // output 2
You should call the first element in an object like this: myObject.key and your key is HardGood.
In arrays it's done like this:
var _Array = [];
_Array .push('x1'); //pushing in array
_Array .push('x2');
console.log(_Array[0]); // getting the first element in that array
Update: if you want to get it dynamically:
var myObject = {"HardGood":362,"Music":2};
for(var key in myObject){
console.log(key +':'+myObject[key]);
}
You have to access JSON object property with . Like below
var myObject = {"HardGood":362,"Music":2};
console.log(myObject.HardGood); //362
Useful links Have a look at below links to understand it better.
Javascript-property-access-dot-notation-vs-brackets
JS-dot-notation-vs-bracket-notation
MDN - OperatorsProperty_Accessors

Get object properties and values from array using lodash/underscore.js

Fiddle Example
I have an array like this:
var array = [ {
'data-price': '0.00',
'data-term': '532',
'data-model_id': '409',
},
{
'data-price': '0.00',
'data-term': '483',
'data-model_id': '384',
},
{ text: 'dffdfddgfdgf' } ];
I want to filter out the last object and extract [{data-model_id:409},{data-model_id:384}] from the first two objects. I have tried this code:
var k = _(array).filter('data-model_id').pluck('data-model_id').value();
console.log(k);
and it returns an array of the values only, ["409", "384"] . Is there a function to return the whole objects in lodash or underscore?
Using plain JS to show the logic: you need to filter out the elements that don't have the key, then map the new collection to another form:
array.filter( function(item){
return 'data-model_id' in item;
}).map( function( item ){
return { 'data-model_id' : item['data-model_id'] }
});
http://jsfiddle.net/dn4tn6xv/7/
What if I told you this is possible using just native javascript? Just use Array.filter and Object.keys, using the former to filter and the latter to get the keys and then returning a Boolean by comparing the index of the Array returned by Object.keys
var k = array.filter(function(obj){
return Object.keys(obj).indexOf("data-model_id") > -1;
});
In lodash you can do like this:
get full object
console.log(_.filter(array, 'data-model_id'));
get only data-model_id property
var res = _.chain(array).filter('data-model_id').map(function (el) {
return _.pick(el, 'data-model_id');
}).value();
Example

Categories