I have a data in array
["Avengers","Batman","Spiderman","IronMan"]
how I can to covert to below
{"Avenger":"Avenger","Batmane":"Batman","Spiderman":"Spiderman","Ironman":"Ironman"}
You can do it like this:
let arr = ["Avengers","Batman","Spiderman","IronMan"];
let obj = arr.reduce((acc, item)=> ({...acc, [item]: item}) , {});
console.log(obj);
Someone else mentioned reduce, but I recommend against, copying objects at every iteration.
Here's a more performant approach.
const arr = ["Avengers","Batman","Spiderman","IronMan"];
const obj = {};
for (const el of arr) {
obj[el] = el;
}
console.log(obj);
You can use reduce to convert array to object.
You can see some examples in here Convert Array to Object
Related
I want to convert an array of objects to object with key value pairs in javascript.
var arr=[{"name1":"value1"},{"name2":"value2"},...}];
How can i convert it to an object such as
{"name1":"value1","name2":"value2",...}
I want it to be supported in majority of browsers.
You could use Object.assign and a spread syntax ... for creating a single object with the given array with objects.
var array = [{ name1: "value1" }, { name2: "value2" }],
object = Object.assign({}, ...array);
console.log(object);
You could run a reduce over the array and return a new object. But it is important to remember that if properties are the same they will be overwritten.
const newObject = array.reduce((current, next) => {
return { ...current, ...next};
}, {})
If you are using es5 and not es6:
var newObject = array.reduce(function(current, next){
return Object.assign({}, current, next);
}, {})
With modern JS (YMMV):
Split each object into entries
Aggregate all entries into one object
const arr = [{name1:"value1"}, {name2:"value2"}, {a:1,b:2}];
const obj = Object.fromEntries(arr.flatMap(Object.entries));
console.log(obj);
Try this simple logic
var arr=[{"name1":"value1"},{"name2":"value2"}];
var obj = {}; //create the empty output object
arr.forEach( function(item){
var key = Object.keys(item)[0]; //take the first key from every object in the array
obj[ key ] = item [ key ]; //assign the key and value to output obj
});
console.log( obj );
use with Array#forEach and Object.keys
var arr = [{"name1": "value1"},{"name2": "value2"}];
var obj = {};
arr.map(k => Object.keys(k).forEach(a => obj[a] = k[a]))
console.log(obj)
Using for...in loop :
var arr=[{"name1":"value1"},{"name2":"value2"}];
var obj = {};
for (var i in arr) {
obj[Object.keys(arr[i])] = arr[i][Object.keys(arr[i])];
}
console.log(obj);
Using Array.map() method with ES6 :
var arr=[{"name1":"value1"},{"name2":"value2"}];
var obj = {};
arr.map(item => obj[Object.keys(item)] = item[Object.keys(item)]);
console.log(obj);
Using Object.assign() method with ES6 spreaqd(...) assignment :
let arr=[{"name1":"value1"},{"name2":"value2"}];
let obj = Object.assign({}, ...arr);
console.log(obj);
How do I convert ["one","two","three"] into {one:"one", two:"two", three:"three"}
import stringArray from './a.js';
class b {
hashmap = stringArray// convert this into Object here inline.
}
Before you jump I know of for how to achieve this in say constructor() with tricks like forEach, for in loop etc. Is there a simple one line code to achieve this in the class property not inside a function.
Lodash
You can use _.zipObject. It accepts two arrays - one for keys, another for values but if you just use the same array twice you'd get matching pairs:
const arr = ["one","two","three"];
const obj = _.zipObject(arr, arr);
console.log(obj);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>
Plain JavaScript
You can use Object.fromEntries to do the same thing. It works with an array of key-value pairs, so you'll have to transform yours to that:
const arr = ["one","two","three"];
const matchingKeyValuePairs = arr.map(x => [x, x]);
const obj = Object.fromEntries(matchingKeyValuePairs);
console.log(obj);
Also you can use Array#reduce to generate an object with a computed property name:
const arr = ["one","two","three"];
const obj = arr.reduce((acc, item) => ({...acc, [item]: item}), {});
console.log(obj);
data = ["one","two","three"];
data = data.map(e => [e,e]) // keyvalue pairs [["one","one"],["two","two"],["three","three"]]
data = Object.fromEntries(data); // {"one":"one","two":"two","three":"three"}
map will convert each element of your input array to a structure you want.
In this case, we want to convert each element to an array with the element repeated twice in it
Object.froEntries will convert a list of key-value pair to an Object
This can be also done with the plain old for loop
data = ["one","two","three"];
obj = {};
for(let i = 0; i < data.length ; i++){
obj[data[i]] = data[i];
}
Try this:
const arr = ["one","two","three"]
let obj = {}
arr.forEach(item => {obj[item] = item})
document.write(JSON.stringify(obj))
Lodash has the _.keyBy() function, that creates an object from an array by generating keys from the values via the function supplied (the iteratee). The default iteratee is _.identity(), which returns the value.
const arr = ["one","two","three"];
const obj = _.keyBy(arr);
console.log(obj);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>
I am trying to convert the nested array to nested obj:
For ex,
let ip_array = [
["fdsfasdf","hghfhgh"],
["fsdf","hjghhjhj"],
["fdfss","hjghh"]
]
expected o/p :
let new_array = [
{"fsdfdsf":""fgdfgdfg},
{"dfdsd":"jhjghj"},
{"dfsddfds":"hghfh"}
]
This can be done with JavaScript's Array.map().
First, you use Array.map() to iterate through the input array, and return the result by using computed property names to set the key/property of each object.
const arr = [["fdsfasdf","hghfhgh"],["fsdf","hjghhjhj"],["fdfss","hjghh"]];
const res = arr.map(element => {
return {
[element[0]]: element[1]
};
});
console.log(res);
You could try
let ip_array = [["fdsfasdf","hghfhgh"],["fsdf","hjghhjhj"],["fdfss","hjghh"]]
let myObj = ip_array.map((a, k) => {
return { [a[0]]: a[1] };
})
An alternative approach using the newer Object.fromEntries() method.
Caution: This is very new method and is still in draft specification at the time of writing this answer in 2019. It may not be cross-browser compatible.
let ip_array = [
["fdsfasdf","hghfhgh"],
["fsdf","hjghhjhj"],
["fdfss","hjghh"]
]
let new_array = ip_array.map((arr)=> Object.fromEntries([arr]));
console.log(new_array);
How can I convert this
[["name", "oni"], ["age",2]]
to
[{name:"oni"}, {age:2}]
You can use .map() to iterate over array and returned value in desired (object) format:
let data = [["name", "oni"], ["age",2]];
let result = data.map(([key, value]) => ({[key]: value}));
console.log(result);
new_array = your_array.map((entry)=>{
return {[entry[0]]: entry[1]}
})
console.log(new_array)
Assuming the properties keys are unique why not create a single object with reduce instead? A single object is much easier to manipulate than an array of objects with one property apiece.
const arr = [["name", "oni"], ["age",2]];
const obj = arr.reduce((acc, c) => {
acc[c[0]] = c[1];
return acc;
}, {});
console.log(obj);
Then just grab the values with dot notation: obj.name, for example.
How can I convert an array of objects to a plain object?
Where each item of the array is an object with only one key:value pair and the key have an unknown name.
I have this
const arrayOfObject = [
{KEY_A: 'asfas'},
{KEY_B: 'asas' }
]
let result = {}
const each = R.forEach((item) => {
const key = R.keys(item)[0]
result[key] = item[key]
})
return result
But I dislike that solution because the forEach is using a global variable result and I'm not sure how to avoid side effects here.
Ramda has a function built-in for this, mergeAll.
const arrayOfObject = [
{KEY_A: 'asfas'}
,{KEY_B: 'asas' }
];
R.mergeAll(arrayOfObject);
//=> {"KEY_A": "asfas", "KEY_B": "asas"}
Since everybody is using ES6 already (const), there is a nice pure ES6 solution:
const arrayOfObject = [
{KEY_A: 'asfas'},
{KEY_B: 'asas'}
];
Object.assign({}, ...arrayOfObject);
//=> {KEY_A: "asfas", KEY_B: "asas"}
Object.assing merges provided objects to the first one, ... is used to expand an array to the list of parameters.
Use reduce instead:
const arrayOfObject = [
{KEY_A: 'asfas'}
,{KEY_B: 'asas' }
];
const each = R.reduce((acc,value) => {
const key = R.keys(value)[0];
acc[key] = value[key];
return acc;
},{},arrayOfObject);
Since your array is an array of objects, you could also just call merge inside a reduce:
const each2 = R.reduce((acc,value) => R.merge(value,acc),{},arrayOfObject);
Here is a jsbin with both examples:
http://jsbin.com/mifohakeru/edit?js,console,output