how can i convert array of objects to one object - javascript

I want to convert object1 to object2 dynamically because keys like apple and water and inside objects are not static.
const object1 = {
apple:[
{a:''},
{b:''}
],
water:[
{c:''},
{d:''}
]
}
convert to this form:
object2 = {
apple:{a:'',b:''},
water:{c:'',d:''}
}

Use Object.entries to iterate the key value pairs, then use Object.assign to merge the inner objects, and finally collect the generated pairs back into one object with Object.fromEntries:
const object1 = {apple:[{a:''},{b:''}],water:[{c:''},{d:''}]}
const object2 = Object.fromEntries(
Object.entries(object1).map(([key, arr]) =>
[key, Object.assign({}, ...arr)]
)
);
console.log(object2);

const object1 = {
apple:[
{a:''},
{b:''}
],
water:[
{c:''},
{d:''}
]
}
let object={}
Object.keys(object1).forEach((item)=>{
let obj={};
object1[item].map((e)=>{
obj={...obj,...e};
});
object[item]=obj;
})
console.log(object)

Related

Convery JS Object to array - keep key & value

I am trying to convert an object (updatedConfig) to an array (configArray), while maintaining the same structure (and avoid further nesting).
I have tried declaring a new array const and using Object.entries to push the keys & values.
I am able to get the keys but am having trouble figuring out how to achieve the nesting of array.
const configArray = [];
Object.entries(updatedConfig).forEach(([key, value]) => {
configArray.push(key);
})
Here is the object in question:
You can try something like this using Object.entries and Array.map
const configObject = {
key1: 'value',
key2: 1,
key3: [1, 2, 3]
}
const configArray = Object.entries(configObject).map(([key, value]) => ({key, value}))
console.log(configArray)

Mapping through an array to produce an object

I have an array :
[
"2022-05-20",
"2022- 06-22",
"2022-06-20"
]
and I want to produce an object like this:
{
'2022-05-20': {disabled:true},
'2022-06-22': {disabled: true},
'2022-06-20': {disabled: true},
}
I tried using a for loop but it kept producing errors. Is this possible with javascript?
You can use Array#reduce as in the following demo. You can also use Array#map but you would have to use Object.fromEntries as well.
const input = [ "2022-05-20", "2022- 06-22", "2022-06-20" ],
output = input.reduce(
(prev,cur) =>
({...prev,[cur]:{disabled:true}}), {}
);
console.log( output );
USING Array#map ...
Here is how you can use Array#map:
const input = [ "2022-05-20", "2022- 06-22", "2022-06-20" ],
output = Object.fromEntries(
input.map(date => [date, {disabled:true}])
);
console.log( output );
Can do it:
let dates = [
"2022-05-20",
"2022- 06-22",
"2022-06-20"
];
let newObj = Object.assign(...dates.map(key => ({[key]: {disabled: true}})));
console.log(newObj)
This might get the job done.
const yourArray = ["2022-05-20", "2022-06-22", "2022-06-20"];
const obj = {};
for(const x of yourArray) obj[String(x)] = { disabled: true };
console.log(obj); // :)
Create the variable obj that is going to save the produced object you want. Iterating throw your array and using a string parsed version of the value in the current iteration (parsing just in case, if you already know the array is made of strings, this is kinda unnecessary) to save it as a key on the new object, also assigning to that key, the value { disabled: true }.
Here is a one liner solution:
let res = data.reduce((acc, curr) =>(acc[curr] = {disabled: true}, acc), {});

How read value from uri key json

i have this object
{
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': '918312asdasc812',
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Login1',
'http://schemas.microsoft.com/ws/2008/06/identity/claims/role': 'User'
}
How read value for key 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier'?
Solution:
obj['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier']
You can put the values of the object in an array and access the array:
const object1 = {
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': '918312asdasc812',
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Login1',
'http://schemas.microsoft.com/ws/2008/06/identity/claims/role': 'User'
};
const arr = (Object.values(object1));
console.log(arr[0]);
to access key, value pairs in an object you can use Object.entries(yourObjName).
foo = {
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': '918312asdasc812',
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Login1',
'http://schemas.microsoft.com/ws/2008/06/identity/claims/role': 'User'
}
for (const [key, value] of Object.entries(foo)) {
console.log(`${key}: ${value}`);
}
read more information on Object.entries()
Thanks #Andy
Solution:
obj['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier']

How to transform object of key - value pairs into array of objects with a single pair JS in a clean way

Basically I have an enum describing status
status = {1: "new", 2: "working" ... }
and I need to take it from that to something like
status = [{1: "new"}, {2: "working"} ...]
in a clean way ... i.e.
something readable, (maybe) simple and reliable. Currently I am not sure how to go about this ... maybe go through the object and "map" each pair to a brand new object in an array? Sounds bad.
Object.entries(data).map(([key, value]) => ({[key]: value}))
The result of the map is the array, what you want.
Or:
const arrayData = [];
for (const key in data) {
arrayData.push({[key]: data[key]})
}
iterate on objects dynamicly:
const object1 = {
a: 'somestring',
b: 42
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
const { object } = require("prop-types")
const status = { 1: "new", 2: "working" }
const statusUpdate = Object.entries(status).map(([key, value]) => ({ [key]: value }))
console.log(statusUpdate);

Way to iterate through object to create array of objects

I have an object that I want to use the keys as keys in a new object and the value into a child object. How could I go from A to Z?
const a = {key1: 'text', key2: 'text2'}
const z = [{ key1: { similarTo: 'text' } }, {key2: {similarTo: 'test2'}}]
You can use Object.entries and Array.prototype.map in order to achieve it:
const a = {key1: 'text', key2: 'text2'};
const z = Object.entries(a).map(([k, v]) => ({ [k]: { similarTo: v } }));
console.log(z);

Categories