Convert object literal notation to array - javascript

I used a literal as a dictionary, but a third party binding tool only takes arrays.
This is one way, is there a better one?
var arr = [];
$.each(objectLiteral, function () { arr.push(this); });

I think there is nothing wrong with your solution.
This is a shorter one:
var arr = $.map(objectLiteral, function (value) { return value; });

Your method is fine, clear and readable. To do it without jQuery, use the for (..in..) syntax:
var arr = [];
for (prop in objectLiteral) {
arr.push(objectLiteral[prop]);
}

In vanilla JS...
If we want to convert an object literal
var obj = {
species: 'canine',
name: 'Charlie',
age: 4
}
into an array of arrays
[['species', 'canine'], ['name', 'Charlie'], ['age', 4]]
here is one way
function objToArr(obj){
var arr = [];
for (var key in obj){
arr.push([key, obj[key]]);
}
return arr;
}

const objectLiteral = { hell: 'devil' };
const ver1 = Object.keys(objectLiteral); // ['hell']
const ver2 = Object.values(objectLiteral); // ['devil']
const ver3 = Object.entries(objectLiteral); // [['hell', 'devil']]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/entries

In ES2017 you can now use Object.entries and with ES6 destructuring support you can use the resulting array pretty nice, example
Object.entries(objectLiteral).filter(([key, value]) => !!value).map(([key, value]) => key)
Gets you all properties with a value

Related

Get object values without using Object.values()

I just started learning to code and am working on this challenge. Having issues finding any relevant guidance online. Thanks in advance.
function keys(json) {
var obj = JSON.parse(json);
let result = [];
for (const key in obj) {
result.push(key);
}
return result;
}
I got this to work for returning keys without using Object.keys and I sort of assumed I could just swap the 'key' for 'value' but that didn't work.
function keys(json) {
var obj = JSON.parse(json);
var values = Object.keys(obj).map((key,value)=>{ values.push(value) });
return values;
}
Also tried this, but I don't really understand the map function yet.
Is this what you are looking for?
const obj = {a:3, b:4}
const result = []
for (const key in obj) {
result.push(obj[key])
}
console.log(result)
With Object.keys you get an array of keys (own, enummerable) of the array. for mapping values, you need to take a property accessor with object and key.
function values(json) {
const object = JSON.parse(json);
return Object
.keys(object)
.map(key => object[key]);
}
console.log(values('{"foo":"bar","baz":42}'));

reactJS adding a object array to and object within an object array

I got a response from a REST call, which returns and array with objects
response.data.steps
For example it looks like this
Now I need to add to each Child of this array an new Object Array.
What could be a smart solution for this problem?
Thanks.
In order to add a new array property to each item, you can simply do:
const steps = response.data.steps.map(step => ({
...step,
newObjectArray: [],
}))
you can usee Array.prototype.map() to do so
let result = response.data.steps.map(element => {
let ret = [element];
return ret;
});
let arr = [{a:1}, {a:2}, {a:3}];
arr = arr.map(element => {
let ret = [element];
return ret;
});
console.log(arr);

Concatenate Object values

I have a JavaScript Object and I'm sure the value of any key is an array (even empty in some case):
{key1:["a","b","c"],key2:["d","e","f"],key3:...}
Aside from using Underscore, is there any way to concatenate all the values of this Object (and create a new array)?
At the moment I get the keys name using Object.keys, then I loop and concatenate.
Any help is appreciated.
var obj = {key1:["a","b","c"],key2:["d","e","f"]};
var arr = Object.keys(obj).reduce(function(res, v) {
return res.concat(obj[v]);
}, []);
// ["a", "b", "c", "d", "e", "f"]
A simple approach is to get the values using Object.values() and concatenate them with [].concat.apply() in this way:
const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = [].concat.apply([], Object.values(_obj))
console.log(_arr)
Another similar way, is to merge Object.values() by spreading them into Array.concat() like this:
const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = [].concat(...Object.values(_obj))
console.log(_arr)
Also reducing each value of the Object.values() and concatenate them, you can get the same result:
const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = Object.values(_obj).reduce((r,c) => r.concat(c), [])
console.log(_arr)
To finish, you can also use Array.prototype.flat() over each value of the Object.values(). Just keep in mind: it's not supported on all browsers.
const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = Object.values(_obj).flat()
console.log(_arr)
Hope this methods could help someone out there :)
Check the array concat function
var obj = {key1:["a","b","c"],key2:["d","e","f"],key3:["g","h"]};
var resultArray = [];
for (var key in obj) resultArray = resultArray.concat(obj[key]);
alert(resultArray);
jsfiddle:
http://jsfiddle.net/qpLq11ea/
Try this:
http://jsfiddle.net/6hbp5bzo/
var arr= [];
var o={key1:["a","b","c"],key2:["d","e","f"]}
for(key in o){
if(o.hasOwnProperty(key)){
arr.push(o[key]);
}
}
alert(arr);

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