javascript: create dictionary from array of key-values objects [duplicate] - javascript

This question already has answers here:
How to convert an array of objects to object with key value pairs
(6 answers)
Merge multiple objects inside the same array into one object [duplicate]
(2 answers)
How to concatenate properties from multiple JavaScript objects
(14 answers)
Closed 1 year ago.
I have an array of objects.
const ar = [ {0 : "A"}, {1 : "B"}];
I want to create an dictionary from it
const di = {0 : "A", 1 : "B"};
I am a little struggling with this conversion. How it is possible to do it using map or reduce?
const di = ar.map( ob => (???) }

A simple reduce can be used to merge all objects. Be aware that the keys need to be unique otherwise you will overwrite them.
The merging is done with the spread syntax
const ar = [{0 : "A"}, {1 : "B"}];
const di = ar.reduce((acc, obj) => ({...acc, ...obj}));
console.log(di);
Another simple approach is the use of Object.assign
const ar = [{0 : "A"}, {1 : "B"}];
const di = Object.assign({}, ...ar);
console.log(di);

You should use reduce here instead of map. map will give you an array of objects but what you need is an object will all keys. So reduce is the best tool for it.
Main difference between map and reduce
const ar = [{ 0: "A" }, { 1: "B" }];
const di = { 0: "A", 1: "B" };
const result = ar.reduce((acc, curr) => {
Object.keys(curr).forEach((k) => (acc[k] = curr[k]));
return acc;
}, {});
console.log(result);

Related

How can I create keys for an array in Javascript? [duplicate]

This question already has answers here:
JS : Convert Array of Strings to Array of Objects
(1 answer)
Convert array of strings to objects and assign specific key
(1 answer)
Closed 3 years ago.
I would like to know how can I create keys for an array of values in javascript like this?
const array = ["NodeJs", "Javascript", "React"]
and transform it like this
const array = [{"name": "NodeJs"}, {"name": "Javascript"}, {"name": "React"}]
Using Array.prototype.map:
const arr = ["NodeJs", "Javascript", "React"];
const newArr = arr.map(name => ({name})); // or arr.map(item => ({name: item}))
console.log(newArr);
You can also do it using Array.from(iterable, mappingFunction) which will return a new array with objects {name: name}:
const array = ["NodeJs", "Javascript", "React"];
const mapArray = Array.from(array, (name) => ({name}));
console.log(mapArray);

JSON object string to convert an array using map [duplicate]

This question already has answers here:
Merge multiple objects inside the same array into one object [duplicate]
(2 answers)
Closed 3 years ago.
Here is my response from my server.
var my_array = [{"1":"1"},{"2":"8"},{"4":"13"},{"5":"19"},{"6":"22"}]; //from server
I want to convert it like
var new_array = { 1 : "1", 2 : "8", 4 : "13", 5 : "19" , 6 : "22"}
But how to convert it using map function
new_array = my_array.map(function (a) {
return ???
});
Use reduce with spreading - you can't map an array to an object. Spreading also allows for multiple properties in each object.
var new_array = my_array.reduce((a, c) => ({ ...a, ...c }), {});
You could also use Object.fromEntries after flatMapping the entries:
var new_array = Object.fromEntries(my_array.flatMap(Object.entries));

Convert array to object keys [duplicate]

This question already has answers here:
Return object with default values from array in Javascript
(4 answers)
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 4 years ago.
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
try with Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
You can use Array.prototype.reduce()and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)

Merge multiple arrays in object [duplicate]

This question already has answers here:
Concatenate Object values
(4 answers)
Closed 7 months ago.
I'm looking at an efficient way to merge multiple array props in an object.
The object, can have multiple array properties in there :
{
"col0Codes": [
"ABC",
"XYZ",
"UYA",
"ZZA",
"AAW",
"MYP"
],
"col1Codes": [
"CNA",
"ZYA",
"OIA",
"POQ",
"LMO",
"OPI"
],
"col2Codes": [
"CNA",
"ZYA",
"OIA",
"POQ",
"LMO",
"OPI"
],
"col3Codes": [
"..."
],
"col4Codes": [
"..."
],
...
}
Result: All the codes in a single array
["ABC","XYZ","UYA","ZZA","AAW","MYP","CNA","ZYA","OIA","POQ","LMO","OPI",....]
I've tried using concat but this creates a new array every single time and overwrites the previous one, I feel this is not fast and memory efficient.
let colCodes = []
for (let i in data) {
colCodes = colCodes .concat(i)
}
console.log(activityCodes)
I've tried using push, but for some reason it does not merge all the entries into one single array but creates a single array with number of props in the object as shown below
let colCodes = []
for (let i in data) {
colCodes.push(i)
}
console.log(colCodes)
[Array(6), Array(5), ....]
Is there anyway I can achieve this using reduce, if that is what'll be fast and mem efficient ?
You can get an array of arrays using Object.values(), and then flatten them to a single array using Array.flat():
const data = {"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
const result = Object.values(data).flat();
console.log(result);
Old answer:
You can get the Object.values(), then merge by spreading into Array.concat():
const data = {"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
const result = [].concat(...Object.values(data));
console.log(result);
You could also simply Array.reduce the Object.values with ES6 spread:
const input={"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
console.log(Object.values(input).reduce((r,c) => [...r, ...c]))
One way would be to use Array.prototype.flat, and call it on the values of the object:
const input={"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
console.log(
Object.values(input).flat()
);
You can try this
let obj = {"col0Codes": ["ABC","XYZ","UYA","ZZA","AAW","MYP"],
"col1Codes": ["CNA","ZYA","OIA","POQ","LMO","OPI"],
"col2Codes": ["CNA","ZYA","OIA","POQ","LMO","OPI"],
"col3Codes": ["..."],
"col4Codes": ["..."]
}
let op = [];
for(let key in obj){
op.push(...obj[key])
}
console.log(op)

JS: Convert An Array Into An Object Without Indexes [duplicate]

This question already has answers here:
Return object with default values from array in Javascript
(4 answers)
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 4 years ago.
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
try with Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
You can use Array.prototype.reduce()and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)

Categories

Resources