from array of objects to an object [duplicate] - javascript

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Closed 3 years ago.
I have an array like this:
array = [{profile: 'pippo'}, {profile: 'mickey'}]
and I would like to transform it to this:
object = {0: 'pippo', 1: 'mickey'}

You can use a short reduce:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = array.reduce((a, o, i) => (a[i] = o.profile, a), {})
console.log(output)
Or even use Object.assign:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = Object.assign({}, array.map(o => o.profile))
console.log(output)
However, your output is in the same format as an array, so you could just use map and access the elements by index (it really just depends on the use case):
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = array.map(o => o.profile)
console.log(output)

Extract the profiles value with Array.map() and spread into an object:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const result = { ...array.map(o => o.profile) }
console.log(result)

using reduce it would be very easy. there you have how it works and a working example.
array = [{
profile: 'pippo'
}, {
profile: 'mickey'
}]
const finalObj = array.reduce((accum, cv, index) => {
accum[index] = cv['profile']
return accum;
}, {})
console.log(finalObj)

Related

need to convert object to JSON value

I have following request body,
{
name1:"john,doe",
name2:"peter,frank"
}
I need to get output as following
{
"name1":["john","doe"],
"name2":["peter","frank"],
}
I am trying to use array methods.
Iterate over the object with for...in, and split the value into an array. Then JSON.stringify the object.
const res = {
name1:"john,doe",
name2:"peter,frank"
};
for (const key in res) {
res[key] = res[key].split(',');
}
console.log(JSON.stringify(res));
You can use Object.entries() and iterate over every key value and convert value into array and get back the new object using Object.fromEntries().
const o = { name1: "john,doe", name2: "peter,frank" },
result = Object.fromEntries(Object
.entries(o)
.map(([key, val]) => ([key, val.split(',')]))
);
console.log(result);

How can I extract from an array of arrays all the arrays that have the same value in their first field?

The following function elegantly finds duplicates in 1-dimensional arrays:
const findDuplicates = (dataArray) => {
const duplicates = dataArray.filter((e, index, arr) => arr.indexOf(e) !== index);
return (duplicates);
};
When I send it (for example) this array
['123456', '787877', '763223', '787877', '854544'] it returns ['787877'].
What I need is something similar that works for a 2-d array so (for instance) inputting
[
['123456', 'Smith'],
['787877', 'Jones'],
['763223', 'Waldo'],
['787877', 'Quagmire'],
['854544', 'Miller']
]
returns
[['787877', 'Jones'], ['787877', 'Quagmire']]
(To be clear, I'm only interested in whether the 1st field of each sub-array is a dupe.)
const findDuplicates = (dataArray) => {
const duplicates = dataArray.filter((e, index, arr) => {
return arr.some((val, i) => (index !== i && val[0] === e[0]))
})
return (duplicates);
};
const result = findDuplicates([
['123456', 'Smith'],
['787877', 'Jones'],
['763223', 'Waldo'],
['787877', 'Quagmire'],
['854544', 'Miller']
])
console.log(result)
You could take an object and use a boolean values to indicae duplicates. Then filter the array.
const
findDuplicates = data => {
const
keys = data.reduce((r, [v]) => {
r[v] = r[v] !== undefined;
return r;
}, {});
return data.filter(([v]) => keys[v]);
},
data = [['123456', 'Smith'], ['787877', 'Jones'], ['763223', 'Waldo'], ['787877', 'Quagmire'], ['854544', 'Miller']],
result = findDuplicates(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Array of Arrays in JavaScript. Replacement for querySnapshot.forEach

so I got this.
const querySnapshot = await getDocs(collectionRef);
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
It outputs the following.
0 => Object
1 => Object
2 => Object
I want an array of arrays. Just like this.
[[0],
[1],
[2]]
Please help
Well you can create and external array and push you values in there like so:
const array = [];
const querySnapshot = await getDocs(collectionRef);
querySnapshot.forEach((doc) => {
array.push([doc.id])
});
console.log(array); // [[0],[1],[2]]
If you reach into docs of the snapshot, you get an array and can use all array operations, such as map:
const arr = querySnapshot.docs.map((doc) => [doc.id]);
console.log(arr);

Get name from JSON JS

In JS I get a response in string ex.
[{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]
And from that I want to only have names, ex.
[{"name":"Cubsonx"},{"name":"Paulina453"}]
and then render every name that is on the list in an discord.js embed fields.
Parse the string to an object:
const jsonObj = '[{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]';
const obj = JSON.parse(jsonObj);
then map the array to the desired one:
const names = obj.map((item) => ({ name: item.name }));
and if you need a string again, then stringify the result:
const stringNames = JSON.stringify(names);
Using _.map from lodash:
const getNames = function(obj) {
return {
name: obj.name
}
}
const data = [{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]
const newArray = _.map(data, getNames)
console.log(newArray) //result: [{"name":"Cubsonx"},{"name":"Paulina453"}]
Using plain JS Array.map MDN: Array.prototype.map
const data = [{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]
const newArray = data.map((item) => ({ name: item.name }))
console.log(newArray) //result: [{"name":"Cubsonx"},{"name":"Paulina453"}]
arr.map((el) => el.name);
This will return an array with names.
Take JSON into obj variable and do
obj.map((element) => element.name)
This will return names

Reversing an Object.entries conversion

I am using Object.entries in order to get some values out of a nested object and filter it.
obj = Object.entries(obj)
.filter(([k, v]) => {
return true; // some irrelevant conditions here
});
My object ends up as an array of arrays, of keys and vals.
[['key1', val]['key2', val]['key3', val]]
Is there a straightforward way to map these back into an object? The original object structure is:
{ key:val, key2:val2, key3:val3 }
Sure, just use .reduce to assign to a new object:
const input = { key:'val', key2:'val2', key3:'val3' };
const output = Object.entries(input)
.filter(([k, v]) => {
return true; // some irrelevant conditions here
})
.reduce((accum, [k, v]) => {
accum[k] = v;
return accum;
}, {});
console.log(output);
In modern browsers, you can also use Object.fromEntries which makes this even easier - you can just pass an array of entries, and it'll create the object from those entries.
const input = { key:'val', key2:'val2', key3:'val3' };
const output = Object.fromEntries(
Object.entries(input)
.filter(([k, v]) => {
return true; // some irrelevant conditions here
})
);
console.log(output);
For new browsers, use Object.fromEntries:
Object.fromEntries(arr);
For older js, it can still be a one liner.
arr.reduce((acc,[k,v])=>(acc[k]=v,acc),{})
Example:
Object.entries(sampleObject) // Turn object to array
.reduce((acc,[k,v])=>(acc[k]=v,acc),{}) // Turn it back to object.
Using Object.assign with a map that maps [k,v] => {[k]: v}
For example, the code below will only keep keys beginning with key
var obj = {
key: 1,
key2: 2,
key3: 3,
removed: 4,
alsoRemoved: 5
}
obj = Object.assign({}, ...Object.entries(obj)
.filter(([k, v]) => {
return k.startsWith('key');
})
.map(([k, v]) => ({[k]: v}))
);
console.log(obj);
Using reduce with deconstruction and comma operator:
const input = { key:'val', key2:'val2', key3:'val3' };
const output = Object.entries(input)
.filter(([k, v]) => {
return true; // some irrelevant conditions here
})
.reduce((acc, [k, v]) => (acc[k] = v, acc), {});
which should give the same functionality as CertainPerformance's answer with a bit more concise syntax
let entries = Object.entries({e: 'e', q: 'q'});
let reverse = entries.map(([t, r]) => ({[t]: r})).reduce((pv, cv) =>{return Object.assign(pv, cv)});
console.log(reverse);
If you know exactly which entries you want to exclude, you can use object deconstruction combined with spreading:
function clean(obj) {
const { unwanted1, unwanted2, ...wanted } = obj;
return { ...wanted };
}
For some cases, this might be the cleanest solution.
function undoEntries(entered){
let output = {};
entered.forEach(item => {
output[item[0]] = item[1]
});
return output;
};
// Example
const obj = { a: 1, b: 2, c: 3};
const input = Object.entries(obj);
const output = undoEntries(input);
console.log(output);

Categories