I have an object of the following structure
const obj = {
[name-1]: 'Peter',
[name-2]: 'Mark',
[name-3]: 'Rich',
[age-1]: 25,
[age-2]: 30,
[age-3]: 45
}
I need to split it into 3 separate object like that
const obj1 = {
[name-1]: 'Peter',
[age-1]: 25,
}
const obj2 = {
[name-2]: 'Mark',
[age-2]: 30,
}
const obj3 = {
[name-3]: 'Rich',
[age-3]: 45,
}
How can I achieve that?
Begin by getting entries of the input object using Object.entries
Reduce over the entries generated in step 1
For each iteration's current value split by delimiter '-'
Reduce it to an object, the object will act as a lookup store
Post doing that just extract the values of the lookup.
Transform the individual entries back to its individual object using Object.fromEntries
const obj = {
'name-1': 'Peter',
'name-2': 'Mark',
'name-3': 'Rich',
'age-1': 25,
'age-2': 30,
'age-3': 45
};
const groupedResult = Object.values(Object.entries(obj).reduce((r, c) => {
const [key, val] = c;
const split = key.split('-');
if (!r[split[1]]) {
r[split[1]] = [c];
} else {
r[split[1]].push(c);
}
return r;
}, Object.create(null)))
.map((value) => Object.fromEntries(value));
console.log(groupedResult);
Related
my json (compact version for better reading)
{
"currency":{
"symbol":"$",
"code":"USD"
},
"prices":{
"data":{
"2022-05-01":{
"property":{
"expectedroomssold_adjusted":6.34,
"exproomssold_l1":3.82
},
"12157":{
"error":false,
"price":7,
"original_price":150.0,
"suggested_price":7,
}
}
}
please tell me the code for replace the date with id in react
You can make a new object and copy all properties of JSON in this object with all properties of date in id and delete the date property from the object
Example
const json = {
a: 5,
b: 7,
"2022-05-22": {
a: 5,
b: 7,
}
};
const id = '2';
const date = "2022-05-22";
const newObj = {
...json,
[id]: {
...json[date]
}
};
delete newObj[date];
console.log(newObj)
I am getting the IDs from an array when I select a few rows (a lot of data is coming in and I only need the IDs). I want that when obtaining the IDs an array is created for me ONLY with the IDs. The problem is that when I try I get the following (by console):
Id Seleccionado: 78
Id Seleccionado: 79
Id Seleccionado: 81
And I would like to obtain them as a normal array:
{ 78, 79, 81 }
TS
procesarClic() {
const request = this.selection.selected;
for (let i = 0; i < request.length; i++){
const list = request[i].id;
console.log('Id Seleccionado: ', list);
}
}
The request constant it is where the selected rows are with all the data in the array, since many rows can be selected.
Thank you for your contribution and help!
You have to create the array and filling it up like this:
procesarClic() {
const request = this.selection.selected;
let array = [];
for (let i = 0; i < request.length; i++){
const list = request[i].id;
console.log('Id Seleccionado: ', list);
array.push(request[i].id);
}
}
This way, you will have an array with only ids in it.
BR
Assuming this.selection.selected is an array which it seems to be, you could use the map function, ie.
const examples = [
{id: 1, name: "One"},
{id: 2, name: "Two"},
{id: 3, name: "Three"}
]
const onlyIds = examples.map(e => e.id);
console.log(onlyIds);
which would return an array consisting of ids only.
I am currently struggling with this problem. Hopefully, you can help me :)
Data is selected from a Database and it returns Objects structured like this:
object = {
id: 4,
name: "Banana",
idParent: 1
}
idParent would be the section of the product.
There are a lot of products and a lot of sections so a simple
const sectionOne = [];
ObjectList.map(e => {
if(e.idParent === 1) {
sectionOne.push(e);
}
})
would probably be wrong, because it should be possible to add other idParents in the future and code should not need some rework in that case.
Let's say there are 30 Objects, 10 have idParent = 1, 15 have idParent = 2 and the last 5 have idParent = 3.
How can the whole list be divided into these sections without making a variable for each section?
Thanks for the help :)
What I believe you need here is a map which groups the values of the list by idParent.
Example:
const objectList = [{
id: 4,
name: "Banana",
idParent: 1
},
{
id: 3,
name: "apple",
idParent: 2
},
{
id: 5,
name: "orange",
idParent: 2
}];
const groupBy = (array, key) => {
return array.reduce((accumlator, value) => {
(accumlator[value[key]] = accumlator[value[key]] || []).push(value);
return accumlator;
}, new Map());
};
const resultMap = groupBy(objectList, "idParent");
console.log(resultMap);
enter code here
The sub-arrays from the map can be access also like this:
const groupWihtIdParen1 = resultMap[1];
// or like this
const groupWithIdParent2 = resultMap.get(2);
``
So I have a dilemma.
I have the next code
const loc = [
{ location_key: [32, 22, 11], autoassign: 1 },
{ location_key: [41, 42], autoassign: 1 }
];
const bulkConfigs = [
{
dataValues: {
config_key: 100,
}
},
{
dataValues: {
config_key: 200,
}
}
];
I need to create an object looking like this:
config_key: here get the config key from from bulkConfigs,
location_key: here get the location_key,
autoassign: 1
Also I need this object created
config_key: config_key,
location_key: '',
autoassign: 1,
as many times as they are locations for each config_key, what I mean is in this example from config_key: 200 we will have 2 objects like this one and for config_key: 100 we will have 3 objects like this. I suppose this can be done with reduce ... also bulkConfigs and loc can have more then just 2 objects, but the number will be always the same, like if they are 3 bulkConfigs there will be also 3 loc, but location_key might be different, one can have 7 location_key, other 4, and the last one just 1.
So in other words, the arrys are always the same length and they are always in the same order so they have the same index. Only the location_key can change, and I need the object created as many times as location_key exist.
I have tried a few things, but I don't know when it comes to this stuff .... I just can't do, that's what happens when you start with react and not java script :)
Ok so I managed to do this using lodash, here is my solution, I know it's nested like hell and probably this could be done way easier, but for a newbie is good enough. Feel free to come with more elegant solutions.
If you have a similar problem, here is the solution.
A code sandbox so you can play with:
https://codesandbox.io/s/epic-field-bdwyi?file=/src/index.js
import _ from "lodash";
const locs = [{ location_key: [32, 22, 11] }, { location_key: [41, 42] }];
const bulkConfigs = [
{
dataValues: {
config_key: 100
}
},
{
dataValues: {
config_key: 200
}
}
];
// map over the array of bulckConfigs and get indexes
const mergedArrays = _.map(bulkConfigs, (bulkConfig, i) => {
// create the object that we need
const objectNeed = {
// flatMap over the locs array to get flat values from objects in it
location_key: _.flatMap(locs, ({ location_key }, index) => {
// match the indexs of both arrays
if (index === i) {
// return the location_key values for each config
return location_key;
} else {
// compact to remove the undefinded values returned
return _.compact();
}
}),
config_key: bulkConfig.dataValues.config_key,
autoassign: 1
};
return objectNeed;
});
// now we just need to crate the same object as many locations and use flatMap to flatten the objects
const allObjects = _.flatMap(mergedArrays, mergedArray => {
const yy = _.map(mergedArray.location_key, location => {
const zz = {
location_key: location,
config_key: mergedArray.config_key,
autoassign: 1
};
return zz;
});
return yy;
});
console.log(allObjects);
And the more elegant version of it :)
const getConfigs = (locEl, index) => {
return _.map(locEl.location_key, (locationKey) => {
return {
location_key: locationKey,
config_key: bulkConfigs[index].dataValues.config_key,
autoassign: 1,
};
});
};
const configLocations = _.chain(locs)
.map(getConfigs)
.flatten()
.value();
console.log(configLocations);
I am Beginner in Ionic 2. I want to add to array element as per their position.
for Ex: i have 2 array .
lables:[Lillium,Gerbera,Gerbera,Lillium,Rose,Rose]
Data : [10, 20, 10, 30, 20,10]
Now I want to remove redundancy from labels[] and want to add their values from data[]
My final array should be
labels: [Lillium,Gerbera,Rose]
data : [40,30,30]
I have Extracted Data from Json this type:
var qp = []
for (var i of res.data) {
qp.push(i.quantity_produced);
console.log(res.data);
console.log(qp);
var name = []
for (var i of res.data) {
name.push(i.product);
var s= [new Set(name)];
console.log(res.data);
console.log(name);
Try this:
let labels = ['Lillium', 'Gerbera', 'Gerbera', 'Lillium', 'Rose', 'Rose'];
let Data = [10, 20, 10, 30, 20, 10];
//for each unique label....
let result = [...new Set(labels)]
//... get each occurence index ...
.map(value => labels.reduce((curr, next, index) => {
if (next == value)
curr.push(index);
return curr;
}, []))
//... and reducing each array of indexes using the Data array gives you the sums
.map(labelIndexes => labelIndexes.reduce((curr, next) => {
return curr + Data[next];
}, 0));
console.log(result);
Based on your comment seems that things can be done a lot easier
let data = [{product: 'Lillium',quantity_produced: 10}, {product: 'Gerbera',quantity_produced: 20},{product: 'Gerbera',quantity_produced: 10}, {product: 'Lillium',quantity_produced: 30}, {product: 'Rose',quantity_produced: 20}, {product: 'Rose',quantity_produced: 10}];
let result = data.reduce((curr, next) => {
curr[next.product] = (curr[next.product] || 0) + next.quantity_produced;
return curr;
}, {});
console.log(result);