This question already has answers here:
Flatten array with objects into 1 object
(12 answers)
Closed 2 years ago.
Can you please help me to create object out of array of objects?
Array to convert arr = [{name:'Ryan'}, {surname:'raynold'}]
required output finalObj = {name:ryan, surname:raynold}
I tried to get the result by doing
let objectArr = Object.assign({}, arr);
but result was like this
{ 0: {shoulder: "14"}, 1:{neck: ""} }
This is a good case for Object.assign.
let arr = [{name:'Ryan'}, {surname:'raynold'}]
let finalObj = Object.assign({}, ...arr);
console.log(finalObj);
Object.assign can take multiple objects as arguments, and so you can spread those objects from your input array. The first argument represents the object in which the others are merged.
You could do it with a array reduce like this:
let finalObj = arr.reduce((acc, cur) => ({...acc, ...cur}), {})
Related
This question already has answers here:
Create an object from an array of keys and an array of values
(9 answers)
Closed 1 year ago.
consider i have an array say
let arr1=["john","Bruce","Clent"];
and
let arr2=[55,33,22];
Then how can i make an object out of this in javascript
object should look like:{"john":55,"Bruce":33,"Clent":22};
it should take arr1 as object's keys and arr2 as object'values
You can just loop the array, but use the index to match the key and value.
const arr1=["john","Bruce","Clent"];
const arr2=[55,33,22];
const obj = {};
arr1.forEach((val, i) => {
obj[val] = arr2[i];
});
This question already has answers here:
Convert JavaScript array of 2 element arrays into object key value pairs
(5 answers)
Closed 3 years ago.
I have an array of objects like this
const jsonx =[{"name":"John Doe"},{"name2":"Marry Doe"},{"name3":"Michael"}]
What I am trying to achieve are the values of each object out of the array as follows
{"name":"John Doe","name2":"Marry Doe","name3":"Michael"}
I have tried the following methods, but did not manage to get what I need.
//console.log(Array.of(...jsonx));
//console.log(JSON.stringify(jsonx));
Alternatively, you can make use of ES6's spread syntax and Object.assign. (My favourite way of doing things)
const jsonx =[{"name":"John Doe"},{"name2":"Marry Doe"},{"name3":"Michael"}];
const res = Object.assign({}, ...jsonx);
console.log(res);
You can try with Array.prototype.reduce()
The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.
and Object.assign()
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
const jsonx =[{"name":"John Doe"},{"name2":"Marry Doe"},{"name3":"Michael"}];
var res = jsonx.reduce((a, c) => Object.assign(a, c), {});
console.log(res);
You can use reduce for it:
const jsonx =[{"name":"John Doe"},{"name2":"Marry Doe"},{"name3":"Michael"}]
const res = jsonx.reduce((acc,curr) => ({...acc, ...curr}), {});
console.log(res)
You can use flatMap() and reduce()
const jsonx =[{"name":"John Doe"},{"name2":"Marry Doe"},{"name3":"Michael"}]
let res = jsonx.flatMap(x => Object.entries(x)).reduce((ac,[k,v]) => ({...ac,[k]:v}),{})
console.log(res)
You can also try
jsonx.reduce((r, a) => Object.assign(r, a))
OR
Object.assign({}, ...jsonx)
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)
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)
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)