How to convert Object into array in jquery/javascript - javascript

I want to convert an object with specific properties into array of string containing properties values. For an instance take Object Employee with below properties with values
Employee.Name='XYZ'
Employee.ID=123
Employee.Address='ABC'
I want this all to be in array as
var arr=['XYZ',123,'ABC']
How to iterate over the properties. Is this possible? Please assist here.

Use $.map()
var arr = $.map(Employee, function(value, key){
return value
})
Demo: Fiddle
Note: The order of loop is not dependable, so the order of values in the array may not be always same
Another way to handle it is to use a fixed array of keys so that the output array will have a predefined sequence
var keys = ['Name', 'ID', 'Address'];
var Employee = {};
Employee.Name = 'XYZ'
Employee.ID = 123
Employee.Address = 'ABC'
var arr = $.map(keys, function (key, idx) {
return Employee[key]
})
console.log(arr)
Demo: Fiddle

Loop through the object like this
var arr = [];
for (var key in Employee) {
arr.push(Employee[key]);
}
Note: Order is not defined in this case

You can loop through each property and add it's value to the array:
var arr = [];
for (var prop in Employee) {
if (Employee.hasOwnProperty(prop)) {
arr.push(Employee[prop]);
}
}
Example - http://jsfiddle.net/infernalbadger/2PHpZ/
Or using jQuery:
var arr = $.map(Employee, function(propValue) {
return propValue;
});
Example - http://jsfiddle.net/infernalbadger/2PHpZ/1/

var myArray=[];
for (var key in Employee) {
if (Employee.hasOwnProperty(key)) {
myArray.push(Employee[key]));
}
}

var Employee = {};
Employee.Name='XYZ';
Employee.ID=123;
Employee.Address='ABC';
var empArray =[];
$.each(Employee,function(item){
empArray.push(item);
});
console.log(empArray);
fiddle

JavaScript since 1.7. Reference to JavaScript language advanced Tips & Tricks.
var arr = [Employee.Name,Employee.ID,Employee.Address];

Related

How to iterate over objects in an array?

I have an array object as mentioned below;
var myArray=[{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}];
I would like to extract the values of dateformat into a separate array, e.g.:
var dateArray=["apr1","apr2","apr3"];
var score=[1,2,3];
I am using a for loop to extract the index but I'm not able to get the values.
Use map to iterate over the initial array objects and return the item you want.
var myArray=[{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}];
var dateArray = myArray.map(function(obj){return obj.dateformat;}),
score = myArray.map(function(obj){return obj.score});
console.log(dateArray);
console.log(score);
Here's the answer as a simple loop.
var dateArray = new Array(myArray.length);
for(var i = 0; i < myArray.length; ++i) {
var value = myArray[i];
var dateValue = value.dateformat;
dateArray[i] = dateValue;
}
You can accomplish the same using the map function:
var dateArray = myArray.map(function(value) { return value.dateformat; });
Create the empty arrays, and use forEach with an argument of 'element' (which represents each object in the array) and push esch of the properties of each object into the required array.
var dateArray=[];
var score=[];
var myArray=[
{dateformat:"apr1", score:1},
{dateformat:"apr2",score:2},
{dateformat:"apr3",score:3}
];
myArray.forEach(function(element) {
dateArray.push(element.dateformat);
score.push(element.score);
});
console.log(dateArray); //gives ["apr1","apr2","apr3"]
console.log(score); //gives ["1","2","3"]
You could use a single loop approach of the given array and iterate the keys and push the values to the wanted arrays.
var myArray = [{ dateformat: "apr1", score: 1 }, { dateformat: "apr2", score: 2 }, { dateformat: "apr3", score: 3 }],
dateArray = [],
score = [];
myArray.forEach(function (target, keys) {
return function(a) {
keys.forEach(function(k, i) {
target[i].push(a[k]);
});
};
}([dateArray, score], ['dateformat', 'score']));
console.log(dateArray);
console.log(score);
If only you don't want to hard code the variables, you could use Array#forEach and Object.keys to store each unique key values inside e.g. array.
Note: It doesn't matter how many keys do you have in your objects, following solution will always return you the right output. Mind that you don't even have to initially declare new variables.
var myArray = [{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}],
obj = {};
myArray.forEach(v => Object.keys(v).forEach(function(c) {
(obj[c] || (obj[c] = [])).push(v[c]);
}));
console.log(obj);

Javascript object in array

Lets say I have a object like
> var products = {a:"b", c:"d", e:"f" ... it goes like this}
i want to put this object in array like this
> var arrList = [[a,b],[c,d],[e,f]]
but i couldnt managed it'll be great if you guys help me thank you already
Just loop and add it to the array
var result = []
for (var key in products) { result.push([key,products[key]]) }
One possible approach:
var arrList = Object.keys(products).map(function(key) {
return [key, products[key]];
});
Note, though, that properties order in objects are not guaranteed in JavaScript.
You can proceed like this:
var products = {a:"b", c:"d", e:"f"};
var arrList = [];
for(var key in products) { // iterates over products key (e.g: a,c,e)
arrList.push([key, products[key]]);
};
Use for-in loop to iterate through object
for (variable in object) => variable is a property name
Try this:
var products = {
a: "b",
c: "d",
e: "f"
};
var arr = [];
for (i in products) {
arr.push([i, products[i]]);
}
snippet.log(JSON.stringify(arr));
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it as follow
products = {a:"b",c:"d",e:"f"};
arrList = [];
for(i in products){
arrList.push([i,products[i]]);
}

How do you search object for a property within property?

I have this object:
key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
And I have an array with only types and I need to add the given image to it, the array looks something like this:
[{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}]
Basically I want to loop the array, find the type in the key object and get the given image and save it into the array.
Is there any simple way to do this?
One thing that stands out here for me is the line
...get the given image and save it into the array
I'm assuming this means the original array. I think a better approach would be to map the appropriate keys and values to a new array but I've assumed, for this example, that it's a requirement.
In an attempt to keep the solution as terse as possible and the request for a lodash solution:
_.each(key, function(prop){
_.each(_.filter(types, { type: prop.type }), function(type) { type.image = prop.img });
});
Given the object of keys and an array of objects like so:
var key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
var arr = [{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}];
We can first create an array of the properties in the object key to make iterating it simpler.
Then loop over the array arr, and upon each member, check with a some loop which image belongs to the member by its type (some returning on the first true and ending the loop).
You can change the forEach to a map (and assign the returned new array to arr or a new variable) if you want the loop to be without side-effects, and not to mutate the original array.
var keyTypes = Object.keys(key);
arr.forEach(function (item) {
keyTypes.some(function (keyType) {
if (key[keyType].type === item.type) {
item.image = key[keyType].img;
return true;
}
return false;
});
});
The smarter thing would be to change the object of the imagetypes so that you could use the type as the accessing property, or create another object for that (as pointed out in another answer).
I'm not sure if this solution is modern, but it does not use any loops or recursion.
object = {
spawn: {type:1, img:app.assets.get('assets/spawn.svg')},
wall: {type:2, img:app.assets.get('assets/wall.svg')},
grass: {type:3, img:app.assets.get('assets/grass.svg')},
spike: {type:4, img:app.assets.get('assets/spike.svg')},
ground: {type:5, img:app.assets.get('assets/ground.svg')}
};
arr = [
{type:1, image:null},
{type:3, image:null},
{type:2, image:null},
{type:2, image:null},
{type:5, image:null}
];
var typeImages = {};
Object.getOwnPropertyNames(object).forEach(function(value){
typeImages[object[value].type] = object[value].img;
});
arr = arr.map(function(value){
return {
type: value.type,
image: typeImages[value.type]
};
});
var key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
var typesArray = [{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}];
for(var i = 0, j = typesArray.length; i < j; i++)
{
typesArray[i].image = getKeyObjectFromType(typesArray[i].type).img;
}
function getKeyObjectFromType(type)
{
for(var k in key)
{
if(key[k].type == type)
{
return key[k];
}
}
return {};
}
for (var i = 0; i < typesArray.length; i++) {
for (prop in key) {
if (key[prop].type === typesArray[i].type) {
typesArray[i].image = key[prop].img;
}
}
}
It loops through the array ("typesArray"), and for each array item, it go through all the objects in key looking for the one with the same "type". When it finds it, it takes that key object's "img" and saves into the array.
Using lodash (https://lodash.com/):
var key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
var initialList = [{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}];
var updatedList = _.transform(initialList, function(result, item) {
item.image = _.find(key, _.matchesProperty('type', item.type)).img;
result.push(item);
});
This will go over every item in the initialList, find the object that matched their type property in key and put it in the image property.
The end result will be in updatedList

Returning only certain properties from an array of objects in Javascript [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 8 years ago.
If I have an object such that
var object = function(key,text)
{
this.key = key;
this.text = text;
}
And create an array of these objects
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
is there a way that I can retrieve only one of the properties of all of the objects in the array? For example:
var keyArray = objArray["key"];
The above example doesn't return set keyArray to anything, but I was hoping it would be set to something like this:
keyArray = [
'key1',
'key2',
'key3']
Does anyone know of a way to do this without iterating through the objArray and manually copying each key property to the key array?
This is easily done with the Array.prototype.map() function:
var keyArray = objArray.map(function(item) { return item["key"]; });
If you are going to do this often, you could write a function that abstracts away the map:
function pluck(array, key) {
return array.map(function(item) { return item[key]; });
}
In fact, the Underscore library has a built-in function called pluck that does exactly that.
var object = function(key,text) {
this.key = key;
this.text = text;
}
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
var keys = objArray.map(function(o,i) {
return o.key;
});
console.log(keys); // ["key1", "key2", "key3"]
JS Bin Example
http://jsbin.com/vamey/1/edit
Note that older browsers may not support map but you can easily do this with a for loop:
var keys = [];
for (var i = 0; i < objArray.length; i++) {
keys.push(objArray[i].key);
}
JS Bin Example
http://jsbin.com/redis/1/edit
You would want to do something like this:
objArray.map(function (obj) { return obj.key; });
Here is a JSFiddle to demo: http://jsfiddle.net/Q7Cb3/
If you need older browser support, you can use your own method:
JSFiddle demo: http://jsfiddle.net/Q7Cb3/1/
function map (arr, func) {
var i = arr.length;
arr = arr.slice();
while (i--) arr[i] = func(arr[i]);
return arr;
}
Well something has to iterate through the elements of the array. You can use .map() to make it look nice:
var keys = objArray.map(function(o) { return o.key; });
You could make a function to generate a function to retrieve a particular key:
function plucker(prop) {
return function(o) {
return o[prop];
};
}
Then:
var keys = objArray.map(plucker("key"));
Really "objArray" is an array that have 3 objects inside, if you want list of keys, you can try this:
var keys = [];
for(a in objArray) {
keys.push(objArray[a].key);
}
You have in var keys, the three keys.
Hope that helps! :)

Javascript: Convert Array to Object

Which is the easiest way to convert this:
[{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}]
to this:
{src:"websrv1", dst:"websrv2", dstport:"80"}
in order to pass it to AJAX data?
I'm using VisualSearch and it returns an array of Facet model instances which i need to convert into an Object.
var a = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var b = a.reduce(
function(reduced,next){
Object.keys(next).forEach(function(key){reduced[key]=next[key];});
return reduced;
}
);
//b should be {src:"websrv1", dst:"websrv2", dstport:"80"}
think about the array.reduce function everytime you need to perform these kind of transformations.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
If you are using jquery, try this:
var array = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}]
var arrayObj = {};
for(var i in array) {
$.extend(arrayObj, array[i]);
}
Use .reduce().
var result = data.reduce(function(obj, item) {
for (var key in item)
obj[key] = item[key];
return obj;
}, {});
Don't use this! but just for fun
var a = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var f = a.reduce((c,d) => Object.assign(c,d), {})
The tiny drawback is that a is mutated with an infinite recursive object but, who cares? it works in one line!
My 2cents, very easy to read:
var myObj = {};
myArray.forEach(function(obj) {
var prop = Object.keys(obj)[0];
myObj[prop] = obj[prop];
})
Original answer using only the most basic features of JavaScript:
var input = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var output = {};
for (var i = 0; i < input.length; i++) {
for (var n in input[i]) {
output[n] = input[i][n];
}
}
console.log(output);
UPDATE: Using newer features of JavaScript, you can do this trivially with Object.assign and spread syntax (...):
var input = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var output = Object.assign({}, ...input);
console.log(output);
Also, Object.assign(...input) will return the same result, but will modify the first element of the input array. As long as you don't mind that side effect, I'd use this simpler version.

Categories

Resources