Converting a dynamic array into single object [duplicate] - javascript

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Closed 2 years ago.
I have a dynamic array which is like this.
var callData = [
{
"FIELD_1": "0763454333"
},
{
"FIELD_2": "dgfdgfg"
},
{
"FIELD_3": "fgfdgfdg"
}
];
According to the user, these number of fields changes. If another user has more fields, there can be FIELD_4, FIELD_5 and so on. I fetch these data from db and put it into and array as above. Now I want to convert it a single object. I want it to look like this.
{
"FIELD_1": "076355998", "FIELD_2": "933504395v", "FIELD_3": "123"
}
Although I found converting solutions in stackoverflow, Those didn't solve my problem. How can I achieve this? Please guide.

use flatMap function to return entries of each object and then use Object.fromEntries function to create an object from the entries
var callData = [
{"FIELD_1": "0763454333" },
{ "FIELD_2": "dgfdgfg" },
{ "FIELD_3": "fgfdgfdg" }
];
const res = Object.fromEntries(callData.flatMap(o => Object.entries(o)));
console.log(res);

Related

SUM AND GROUPING JSON DATA USING JAVASCRIPT [duplicate]

This question already has answers here:
How to group by and sum an array of objects? [duplicate]
(2 answers)
Sum JavaScript object propertyA values with the same object propertyB in an array of objects
(12 answers)
Group by, and sum, and generate an object for each array in JavaScript
(4 answers)
ES6 Implementation of Group By and SUM
(4 answers)
Javascript array of objects group and sum items
(4 answers)
Closed last year.
Sorry if this has been asked before, but I couldn't find a good example of what I'm trying to accomplish. Maybe I'm just not searching for the right thing. Please correct me if there's an explanation of this somewhere.
so let's says I have a data like this :
data = [
{"no":1,"location":"New York","transaction":3000},
{"no":2,"location":"Tokyo","transaction":3000},
{"no":3,"location":"New York","transaction":3000},
{"no":4,"location":"Amsterdam","transaction":3000},
{"no":5,"location":"Manchester","transaction":3000},
{"no":6,"location":"New York","transaction":3000},
{"no":7,"location":"Tokyo","transaction":3000},
{"no":8,"location":"Tokyo","transaction":3000},
{"no":9,"location":"New York","transaction":3000},
{"no":10,"location":"Amsterdam","transaction":3000}
]
what i wanted to is an output like this :
result = [
{"location":"New York","transaction":12000},
{"location":"Tokyo","transaction":9000},
{"location":"Amsterdam","transaction":6000}
{"location":"Manchester","transaction":3000}
]
so what i wanted to do is grouping the data based on location and sum the transaction where the location is same and push the data to another array. i don't know where to start, need some help to solve this or any suggestion to solve this using Javascript. thank you
Working Demo :
// Input array
const data = [
{"no":1,"location":"New York","transaction":3000},
{"no":2,"location":"Tokyo","transaction":3000},
{"no":3,"location":"New York","transaction":3000},
{"no":4,"location":"Amsterdam","transaction":3000},
{"no":5,"location":"Manchester","transaction":3000},
{"no":6,"location":"New York","transaction":3000},
{"no":7,"location":"Tokyo","transaction":3000},
{"no":8,"location":"Tokyo","transaction":3000},
{"no":9,"location":"New York","transaction":3000},
{"no":10,"location":"Amsterdam","transaction":3000}
];
// result array
const resultArr = [];
// grouping by location and resulting with an object using Array.reduce() method
const groupByLocation = data.reduce((group, item) => {
const { location } = item;
group[location] = group[location] ?? [];
group[location].push(item.transaction);
return group;
}, {});
// Finally calculating the sum based on the location array we have.
Object.keys(groupByLocation).forEach((item) => {
groupByLocation[item] = groupByLocation[item].reduce((a, b) => a + b);
resultArr.push({
'location': item,
'transaction': groupByLocation[item]
})
})
console.log(resultArr)

Convert a string to a nested JavaScript object or JSON [duplicate]

This question already has answers here:
Javascript nested objects from string
(5 answers)
Closed 1 year ago.
I have the following string:
let str = "modules.mas.mas-helper-provider.assets.locales";
and would like to convert it to a nested JavaScript object (JSON), something like this result:
{
"modules": {
"mas": {
"mas-helper-provider": {
"assets": {
"locales": ""
}
}
}
}
}
You can split the string to an array, then reduceRight to create an object by reading each key.
let str = "modules.mas.mas-helper-provider.assets.locales";
var newObject = str.split(".").reduceRight((obj, next) => ({
[next]: obj
}), "");
console.log(newObject);

JavaScript array manipulation interview question [duplicate]

This question already has answers here:
Merge objects with same id in array
(7 answers)
Closed 1 year ago.
This is a question that I have encountered during an interview:
Write a function to transform the array:
[
{name:'a',values:[1,2]},
{name:'b',values:[3]},
{name:'a',values:[4,5]}
]
to:
[
{name:'a',values:[1,2,4,5]},
{name:'b',values:[3]}
]
I know this is not hard, but I just can't figure it out.
Does anyone know how to solve it?
Are there any places that I can find and practice more practical questions like this one?
You can group the array by name and then get an array using the grouped object:
const bla = [
{name:'a',values:[1,2]},
{name:'b',values:[3]},
{name:'a',values:[4,5]}
];
const res = Object.values(bla.reduce((obj, { name, values }) => {
obj[name] = obj[name] ?? {name, values: []}
obj[name].values.push(...values)
return obj
}, {}));
console.log(res)

Sort Javascript Object by Value [best practices?] [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 5 years ago.
Since there's no official way to sort an object by values, I'm guessing you either (1) Use an array instead or (2) Convert your object to an array using Object.entries(), sort it, then convert back to an object. But option (2) is technically unsafe since Javascript objects aren't supposed to have order.
Now I have a React app where I'm using Redux. I'm storing my data not as an array but as an object iterated by id values. This is what Redux suggests, and I would do it anyways, because of lookup times. I want to sort this redux data, so what I'm currently doing is option (2) of converting to array and then back to object. Which I don't really like.
My question is: Is this what everyone else does? Is it safe to sort an object?
Example:
const sortObject = (obj) => {
//return sorted object
}
var foo = {a: 234, b: 12, c: 130}
sortObject(foo) // {b: 12, c:130, a:234}
this is what I'm currently doing.
My object data structure looks something like this
obj = {
asjsd8jsadf: {
timestamp: 1234432832
},
nsduf8h3u29sjd: {
timestamp: 239084294
}
}
And this is how I'm sorting it
const sortObj = obj => {
const objArray = Object.entries(obj);
objArray.sort((a, b) => {
return a[1].timestamp < b[1].timestamp ? 1 : -1;
});
const objSorted = {};
objArray.forEach(key => {
objSorted[key[0]] = key[1];
});
return objSorted;
};
If you are using the Redux documentation for reference you should also have an array with all of the id's in it. Wouldn't it be easier to just sort that array and then use insertion sort when you add something to the state. Then you could use the sorted array to access the byId property of the state?

How do I sort an array filled with objects, based on two values of the object? [duplicate]

This question already has answers here:
Sort by two values prioritizing on one of them
(8 answers)
Closed 8 years ago.
I've got an array populated with objects. These objects start with two values: sort1 and sort2.
var arr_obj = [
{
sort1:'3000',
sort2:'200',
value:'Value1'
},
{
sort1:'4000',
sort2:'100',
value:'Value2'
},
{
sort1:'6000',
sort2:'200',
value:'Value3'
},
{
sort1:'6000',
sort2:'100',
value:'Value4'
},
{
sort1:'2000',
sort2:'500',
value:'Value5'
}
];
How do I go about sorting the objects based on the values of sort1 and sort2. Sort1 is dominant and if two values have the same sort1 value then the sort function should look at sort2 to determine which one comes first.
So for my example array the output should become.
[
{
sort1:'2000',
sort2:'500',
value:'Value5'
},
{
sort1:'3000',
sort2:'200',
value:'Value1'
},
{
sort1:'4000',
sort2:'100',
value:'Value2'
},
{
sort1:'6000',
sort2:'100',
value:'Value4'
},
{
sort1:'6000',
sort2:'200',
value:'Value3'
}
];
I tried just using a simple sort() on the array, but this probably looks at the index not the first values.
Does anyone know how to get the requested output?
FIDDLE
You can set a compare function into the sort.
arr_obj.sort(function(a,b) {
if (a.sort1 === b.sort1) {
return a.sort2 - b.sort2;
}
return a.sort1 - b.sort1;
});
Try this:-
arr_obj.sort(function(prev,next){
if(prev.sort1 != next.sort1){
return prev.sort1 > next.sort1;
}else{
return prev.sort2 > next.sort2;
}
});

Categories

Resources