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);
Related
I would like to know how to fetch the keys in object contains only underscore in javascript.
I would like to get the output with text before underscore, as shown
var obj={
cn_start: "SG",
cn_end:"TH",
cn1_start:"ML",
cn1_end:"IN"
}
Expected Output
[
cn, cn1
]
I believe using reduce is better, but for better readability, I use for loop.
First, you get the keys using Object.keys, then iterate the keys finding the ones with '_' and push the prefix if it does not exists yet.
var obj={
cn_start: "SG",
cn_end:"TH",
cn1_start:"ML",
cn1_end:"IN"
}
const keys = Object.keys(obj);
let underscoreKeys = [];
keys.forEach(key => {
if(key.substring('_')){
const prefix = key.split('_')[0];
if(underscoreKeys.indexOf(prefix) < 0){
underscoreKeys.push(prefix);
}
}
});
console.log(underscoreKeys);
For an Internet Explorer compatible answer, try the following:
var obj={
cn_start: "SG",
cn_end:"TH",
cn1_start:"ML",
cn1_end:"IN"
}
var objkeys = Object.keys(obj);
var underscorekeys = [];
for(var i = 0; i < objkeys.length; i++) {
var index = objkeys[i].indexOf("_");
if(index > -1) {
var prefix = objkeys[i].substr(0, index);
if(underscorekeys.indexOf(prefix) < 0)
underscorekeys.push(prefix);
}
}
console.log(underscorekeys);
The other answers use 'arrow functions' or 'lambda functions' which is ES6 and not IE compatible.
You can grab the keys from your object using Object.keys(), then filter out all the keys which don't have an underscore in them. Next, you can .map() each key to a substring of itself by removing the underscore _ and its trailing text (using .replace(/_.+/, '')). You can then use a new Set to remove any duplicates, and Array.from to turn that set back into an array:
const obj={
cn_start: "SG",
cn_end:"TH",
cn1_start:"ML",
cn1_end:"IN"
}
const get_keys = obj =>
Array.from(new Set(Object.keys(obj).filter(k => k.includes('_')).map(k => k.replace(/_.+/, ''))));
console.log(get_keys(obj));
If you know all your keys will have an underscore in them, then you can remove the .filter().
Split the key names by '_' and add them to Set to get unique keys.
var obj = {
cn_start: "SG",
cn_end: "TH",
cn1_start: "ML",
cn1_end: "IN"
};
const keys = [...new Set(Object.keys(obj).map(key => key.split("_")[0]))];
console.log(keys);
const keysNames = Object.keys(myObj);//returns the array ['keyName','keyName'];
I have two arrays and I need to make it as object of array
var arr1 = [1,2,3,4,5]
var arr2 = [a,b,c]
Is there any possibility to change the array to this format[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
Could someone help me?
Try this code:
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = arr2.reduce(function(obj, item) {
obj[item] = arr1.slice(); // or = arr1 to keep the reference
return obj;
}, {});
console.log(result); // {"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
You have 2 cases:
To create clones of the array use result[item] = arr1.slice();
To keep the reference to the same array use result[item] = arr1;
Check more about the reduce() method.
I am assuming you need a object like this
{"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
So you can do it like this.
var arr1 = [1,2,3,4,5]
var arr2 = ["a","b","c"];
var result={}
arr2.map(function(k){
result[k]=arr1;
})
console.log(result);
But here I am giving values of keys as arr1 reference so if arr1 will change value of keys in result will also change.
Is there any possibility to change the array to this
formate[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
This is neither an array format nor a valid JSON literal, so this format could only be a string.
Assuming that you are looking for a string in the format you have specified
var output = "[" + arr2.map(function(value){return value+",{" + arr1.join(",") + "}"}).join("],[") + "]";
Use forEach to iterate through List and get your desired result.
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = {} // Result: Object of Array
arr2.forEach(function(val, index) {
result[val] = arr1;
})
I hope this is easy to understand :)
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]]);
}
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.
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