Combine array of objects into a single object [duplicate] - javascript

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Convert Javascript array of objects into one object
(4 answers)
How to convert array of objects in one specific object?
(9 answers)
shortest way to create a comma separated object list [duplicate]
(2 answers)
Closed 2 years ago.
I have data that looks like this.
[
{
key: 'myKey'
value: 'myValue'
},
{
key: 'mySecondKey'
value: 'mySecondValue'
},
{
key: 'myThirdKey'
value: 'myThirdValue'
},
]
The amount of objects varies depending on how much values an account has set. I'm trying to return this in a format that looks like this
{
mykey: 'myValue'
mySecondKey: 'mySecondValue'
myThirdkey: 'myThirdValue'
}
Any advice on how I would go about doing this?

You can do something, like
const src = [{key:'myKey',value:'myValue'},{key:'mySecondKey',value:'mySecondValue'},{key:'myThirdKey',value:'myThirdValue'},],
result = Object.assign({}, ...src.map(o => ({[o.key]: o.value})))
console.log(result)
.as-console-wrapper{min-height:100%;}

You can use reduce for this:
const data = [{key:"myKey",value:"myValue"},{key:"mySecondKey",value:"mySecondValue"},{key:"myThirdKey",value:"myThirdValue"}];
const res = data.reduce((obj, {key, value}) => ({...obj, [key]: value}), {});
console.log(res);

Other answers work but I feel like they are a bit complicated, here's a simple for of loop:
const data = [
{
key: 'myKey',
value: 'myValue'
},
{
key: 'mySecondKey',
value: 'mySecondValue'
},
{
key: 'myThirdKey',
value: 'myThirdValue'
}
];
const result = {};
for(const {key, value} of data) {
result[key] = value;
}
console.log(result);

Related

How to create array of objects from array: javascript [duplicate]

This question already has answers here:
How to convert array of items to array of objects?
(2 answers)
Closed 1 year ago.
I am trying to convert an array of elements to an array of objects in Javascript (react)
Here is the data I am getting from my API
"versions": [
"1.0.1.2",
"1.0.22.0",
"1.1.0.12",
"2.5.2.6",
"2.5.2.7",
"2.7.5.11",
"2.7.7.7",
"3.9.2.94",
"3.9.3",
"5.2.0.87",
"9.5.0.210" ]
And I am trying to convert to an array of object which should look like this
options = [
{ value: "1.0.1.2", label: "1.0.1.2" },
{ value: "1.0.22.0", label: "1.0.22.0" },
{ value: "2.5.2.6", label: "2.5.2.6" },
];
I tried using the map function
versions = VersionloginData.data.versions.map((version) => [version.value, version.label])
But didn't work out well , i am getting undefined as value objects
You needed to return an object inside the map callback:
versions = VersionloginData.data.versions.map((version) => ({ value: version, label: version }))
Its should be.
const data = {
"versions": [
"1.0.1.2",
"1.0.22.0",
"1.1.0.12",
"2.5.2.6",
"2.5.2.7",
"2.7.5.11",
"2.7.7.7",
"3.9.2.94",
"3.9.3",
"5.2.0.87",
"9.5.0.210"]
}
const output = data.versions.map(item => ({ value: item, label: item }));
console.log(output);
Why your code is not working?
You are accessing incorrect nodes with [version.value, version.label]. value and label doesnot exist on version. Instead, you should return an object with keys value and label having same value.
you can try this
var options = []
versions.forEach((v)=>{
options.push({
value: v,
label: v,
})
})

How to insert value from an array to an array of object [duplicate]

This question already has answers here:
Convert array of strings into an array of objects
(6 answers)
Closed 1 year ago.
I might need some help on JavaScript about array stuff.
[
"URL_1",
"URL_2",
"URL_3",
"URL_4",
...,
"URL_30"
]
Let's just say these above are an array of strings which are links and how do I move them to an array object like this below?
[
{
url: "URL_1"
},
{
url: "URL_2"
},
{
url: "URL_3"
},
...,
{
url: "URL_30"
}
]
Using Array#map:
const arr = [ "URL_1", "URL_2", "URL_3", "URL_4", "URL_30" ];
const res = arr.map(url => ({ url }));
console.log(res);
simply:
let temp = [];
yourArray.foreach((val) =>{
temp.push({val})
})
yourArray = temp;

Convert array to map [duplicate]

This question already has answers here:
How to convert an array of objects to object with key value pairs
(6 answers)
Closed 2 years ago.
I am trying to convert a array of unique ids to a flat map of theses
const arr = [ { user1: 'val' }, { user2: 'val' } ]
and I want to convert to
{ user1: 'val', user2: 'val' }
How can I do this?
Using array.reduce
arr.reduce((obj, val) => ({...obj, ...val}))

How to convert JSON Object into key value pair in JS? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
{"1":"val1","2":"val2","3":"val3"}
i want it to converted like this:
{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
little Help Please would be much appricated
You can't use the same key name in one object.
instead you can do this.
const origin = {"1":"val1","2":"val2","3":"val3"}
const converted = Object.entries(origin).map( ([key,value]) => ({id: key, value }) );
console.log(converted);
What you have posted is invalid.
What you might want is:
const object = {"1":"val1","2":"val2","3":"val3"};
console.log(Object.entries(object));
// or
console.log(Object.keys(object).map(i => ({Id: i, value: object[i]})));
You could use a loop over Object.entries.
E.g. something like:
const newObjArr = [];
for(let [key, value] of Object.entries(obj)){
newObj.push({Id: key, value});
}
The above would return an array of objects, but I'm sure you can amend it to your particular use case.
const data = {"1":"val1","2":"val2","3":"val3"};
const result = Object.keys(data).map((key) => ({ id: key, value: data[key] }));
The result will be [{ id: "1", value: "val1" }, { id: "2", value: "val2" }, { id: "3", value: "val3" }]
As pointed out this is invalis. If you want to convert it if would look like this:
[{"Id":"1","value":"val1"},{"Id":"2","value":"val2"},{"Id":"3","value":"val3"}]
You can make an function that converts this.
const object = {"1":"val1","2":"val2","3":"val3"};
console.log(Convert(object));
function Convert(obj){
return Object.keys(obj).map(i => ({Id: i, value: obj[i]}));
}
You cannot do this. Object is a unique key value pair.
{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
Suppose you want to merge two object and What if both the object has same key, it simply merge the last objects value and have only one key value.
You can convert your large object to several small objects and store them in an array as this snippet shows. (It could be much shorter, but this verbose demo should be easier to understand.)
// Defines a single object with several properties
const originalObject = { "1" : "val1", "2" : "val2", "3" : "val3" }
// Defines an empty array where we can add small objects
const destinationArray = [];
// Object.entries gives us an array of "entries", which are length-2 arrays
const entries = Object.entries(originalObject);
// `for...of` loops through an array
for(let currentEntry of entries){
// Each "entry" is an array with two elements
const theKey = currentEntry[0]; // First element is the key
const theValue = currentEntry[1]; // Second element is the value
// Uses the two elements as values in a new object
const smallObject = { id: theKey, value: theValue };
// Adds the new object to our array
destinationArray.push(smallObject);
} // End of for loop (reiterates if there are more entries)
// Prints completed array of small objects to the browser console
console.log(destinationArray);
const obj = {"1":"val1","2":"val2","3":"val3"}
const newObject = Object.keys(obj).map(e => {
return {ID: e , value : obj[e] }
});
console.log(newObject); // [ { ID: '1', value: 'val1' },
{ ID: '2', value: 'val2' },
{ ID: '3', value: 'val3' } ]
it will give u an array of object, later u need to convert it to object and flat the object:
How do I convert array of Objects into one Object in JavaScript?
how to convert this nested object into a flat object?

JavaScript: Dynamically generated object key [duplicate]

This question already has answers here:
Creating object with dynamic keys [duplicate]
(2 answers)
Closed 5 years ago.
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
]
const output = []
Object.keys(cars).map((car) => {
output.push({
foo: cars[car].defaultCategory
})
})
console.log(output)
This work fine, however what I want to achieve is so that the newly crated object has structure of 'truck': 'vehicle'.
So if I replace push argument with
${cars[car].id}`: cars[car].defaultCategory
I get SyntaxError: Unexpected template string
What am I doing wrong?
Use map on the array, and not the keys (the indexes) to get an array of objects. For each object use computed property names to set the id value as the key:
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
];
const result = cars.map(({ id, defaultCategory }) => ({ [id]: defaultCategory }));
console.log(result);
You should use .map() over your cars array and not Object.keys(cars):, we don't use Object.keys() with arrays.
This is how should be your code:
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
var cars = [{
'id': 'truck',
'defaultCategory': 'vehicle'
}];
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
console.log(output);

Categories