array with objects containing array - reactjs

Sorry guys if my way of asking the question in the title is not correct.
I am working on a project on react js and I am getting the data like this
[
{
"count": [
{
"1": 16
},
{
"1": 149
}
],
"day": "2019-08-27"
}
]
now this is my first time I am dealing with this kind of data and I really have no idea how can I show it like this I am really sorry guys I literally can't even show what I have tried because it does not seem relevant
[
{
count: 165
day:"2019-08-27"
}
}

Assuming the data you're getting is under a variable called data you could use reduce:
The below makes the assumption the count is always an array of objects with just 1 key called '1'.
const newData = data.map(datum => {
datum.count = datum.count.reduce((count, item) => {
return count + item['1']
}, 0)
return datum
})

You can try something like this:
let arr = [
// item
{
count: [
{
"1": 16
},
{
"1": 149
}
],
day: "2019-08-27"
}
];
arr.map(item => {
Object.keys(item).map(key => {
console.log(item[key])
// if item[key] is iterable
if(Array.isArray(item[key])) {
item[key].map(val => {
console.log(item)
})
} else {
console.log(item[key])
}
});
});
The concept is that for Objects you do a Object.keys().something and for an array you do a arr.map(item => ...)

Related

Replace a string in array of objects in typescript

I have got a list of array objects as shown below
[
{
"subjectID": 1
"Chosen" : "{subjectsChosen:Python,java,Angular}"
"password": "{studentpw:123456abcd}"
},
{
"subjectID": 2
"Chosen" : "{subjectsChosen:SQL,Rprogram,React}"
"password": "{studentpw:987654zyxwv}"
}
]
Here I would like to remove the special characters and its notations and expected to populate array as shown below using typescript
[
{
"subjectID": 1
"Chosen" : "Python,java,Angular"
"password": "23456abcd"
},
{
"subjectID": 2
"Chosen" : "SQL,Rprogram,React"
"password": "987654zyxwv"
}
]
Thank you in advance
try this
for (let i = 0; i < subs.length; i++) {
subs[i].Chosen = removeSymbols(subs[i].Chosen);
subs[i].password = removeSymbols(subs[i].password);
}
function removeSymbols(s: string) {
return s.replace(/[\{\}]/g, "").split(":")[1];
}
result
[
{
"subjectID": 1,
"Chosen": "Python,java,Angular",
"password": "123456abcd"
},
{
"subjectID": 2,
"Chosen": "SQL,Rprogram,React",
"password": "987654zyxwv"
}
]
Welcome, is your object properties special characters limited to '{', ':', '}', if so, I propose to you the bellow solution, that I have tried and give a result as the one you have expected:
let objs = [
{
subjectID: 1,
Chosen: "{subjectsChosen:Python,java,Angular}",
password: "{studentpw:123456abcd}"
},
{
subjectID: 2,
Chosen: "{subjectsChosen:SQL,Rprogram,React}",
password: "{studentpw:987654zyxwv}",
}
];
objs.forEach((cur) => {
Object.keys(cur).forEach(key => {
if (typeof cur[key] === 'string') {
cur[key]=cur[key].replace(/[\{\}]/g, '').split(':')[1];
}
})
});
console.log(objs);
You could use any array operator function other than forEach.
We could use map operator of Array here to transform each item. To transform Chosen and password fields, we could use Regex and replace method of string.
const chosenRegex = new RegExp(/\{subjectsChosen:(.+)\}/, 'i')
const myText = "{subjectsChosen:Python,java,Angular}";
myText.replace(re, '$1'); // Python,java,Angular
Below is the full implementation that transform each item.
const items = [
{
"subjectID": 1,
"Chosen" : "{subjectsChosen:Python,java,Angular}",
"password": "{studentpw:123456abcd}"
},
{
"subjectID": 2,
"Chosen" : "{subjectsChosen:SQL,Rprogram,React}",
"password": "{studentpw:987654zyxwv}"
}
];
const chosenRegex = new RegExp(/\{subjectsChosen:(.+)\}/, 'i')
const passwordRegex = new RegExp(/\{studentpw:(.+)\}/, 'i')
const transformedItems = items.map(item => {
return {
...item,
"Chosen": item.Chosen.replace(chosenRegex, '$1'),
"password": item.password.replace(passwordRegex, '$1')
}
});
console.log(transformedItems);
We could also literally use a single regex if we don't want to differentiate them.
const transformRegex = new RegExp(/\{(.+):(.+)\}/, 'i');
....
return {
...item,
"Chosen": item.Chosen.replace(transformRegex, '$2'), // Since there are two regex groups now, use $2
"password": item.password.replace(transformRegex, '$2')
}

Typescript - Querying or flattening nested array but keeping some objects as nested ones

Again I'm stuck with a nested Array of objects. I want to flatten it out, but I do have to keep some nested objects. The Problem I'm running into: How to rename the keys of the nested objects since I have an undefined number of nested objects. There might be 3 of them oder 8. So property1_3 has to be renamed to eg property1_3_1, property1_3_2 - depending on how many objects are in the original json data. And how to aply them to the correct parent object.
The json data I recieve looks like:
data = [{
"property1_1": "value1_1",
"property1_2": "value1_2",
"property1_3": [
[{
"subproperty1_1_1": "subvalue1_1_1",
"subproperty1_1_2": "subvalue1_1_2"
}],
[{
"subproperty1_2_1": "subvalue1_2_1",
"subproperty1_2_2": "subvalue1_2_2"
}]
]
},
{
"property2_1": "value2_1",
"property2_2": "value2_2",
"property2_3": [
[{
"subproperty2_1_1": "subvalue2_2_1",
"subproperty2_1_2": "subvalue2_2_2"
}],
[{
"subproperty2_2_1": "subvalue2_2_1",
"subproperty2_2_2": "subvalue2_2_2"
}],
[{
"subproperty2_3_1": "subvalue2_2_1",
"subproperty2_3_2": "subvalue2_2_2"
}]
]
}
]
What I want to achieve now is:
data = [
{
"property1_1": "value1_1",
"property1_2": "value1_2",
"property1_3_index1": {"subproperty1_1_1":"subvalue1_1_1", "subproperty1_1_2":"subvalue1_1_2"},
"property1_3_index2": {"subproperty1_2_1":"subvalue1_2_1", "subproperty1_2_2":"subvalue1_2_2"}
},
{
"property2_1": "value2_1",
"property2_2": "value2_2",
"property2_3_index1": {"subproperty2_1_1":"subvalue2_2_1", "subproperty2_1_2":"subvalue2_2_2"},
"property2_3_index2": {"subproperty2_2_1":"subvalue2_2_1", "subproperty2_2_2":"subvalue2_2_2"},
"property2_3_index3": {"subproperty2_3_1":"subvalue2_2_1", "subproperty2_3_2":"subvalue2_2_2"}
}
]
My last try was:
transformData(input) {
const testArray = [];
input.map(obj => {
for (const prop in obj) {
if (obj.hasOwnProperty(prop) && Array.isArray(obj[prop])) {
for (const [index, element] of obj[prop].entries()) {
testArray.push(element[0]);
}
}
}
});
}
but this only leeds to an array with all the single subobjects in one array. I'm also not quite sure if it's best trying to convert the original data or to build a new array as I tried before.
I finally found a way to achieve this.
transformData(input) {
return input.map(obj => {
for (const prop in obj) {
if (obj.hasOwnProperty(prop) && Array.isArray(obj[prop])) {
for (let i = 0; i < obj[prop].length; i++) {
const name = prop + (i + 1).toString();
obj[name] = obj[prop].flat(1)[i];
}
delete obj[prop];
}
}
return obj;
});
}

Is there any way to update state by find Item and replace on a nested state?

I am building an order functionality of my modules in the component state on react
so the state object looks like that
"activity": {
"name": "rewwerwer",
"description": "werwerwerwerwer",
"modules": [
{
"name": "Text",
"order": 1,
"module_id": 1612,
},
{
"name": "Text2",
"order" 2,
"module_id": 1592,
}
]
}
handleSortUp = (moduleid ,newOrder) => {
const { modules } = this.state.activity;
const module = modules.find(element => element.module_id === moduleid);//Thios returns the correct object
this.setState({ activity: { ...this.state.activity.modules.find(element => element.module_id === moduleid), order: newOrder } });
}
I tried this but it updates the order field and object
but also removes all other objects from modules array :<
I like just to replace only the order field on each module by module id
and leave rest data there
the required response from the state that i need when the handleSortUp(1612,14); is fired
handleSortUp(1612,2);
{
"name": "rewwerwer",
"description": "werwerwerwerwer",
"modules": [
{
"name": "Text",
"order": 2,
"module_id": 1612,
},
{
"name": "Text2",
"order": 1,
"module_id": 1592,
}
]
}
I can do this on a simple array the question is how to update the State on react
Also the one way to change the order is answered fine but how also to change the field that had that order registered
So when we fire Change Item 1 order to 2 the Item 2 needs to take the Order 1
Thank you
Sure! This would be a great place to use the built-in .map method available for arrays. Consider the following example.
let array = [{order: 1, type: "food"}, {order: 2, type: "notfood"} ]
const newArray = array.map((item) => {
//CHECK TO SEE IF THIS IS THE ITEM WE WANT TO UPDATE
if(item.order == 1){
return {
...item,
newField: "newData"
}
} else {
return item
}
})
Output is:
[{order: 1, type: "food", newField: "newData"}
{order: 2, type: "notfood"}]
So yes you could totally update the module you're looking for without mutating the rest of your array. Then use your findings to update the component state using some good ol spread.
this.setState({
activity: {
...this.state.activity,
modules: newArray}
})
Of course they get all eliminated. Pay attention to what you wrote here:
this.setState({ activity: { ...this.state.activity.modules.find(element => element.module_id === moduleid), order: newOrder } });
What are you doing with that find? Let's see what Array.prototype.find() returns: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Array/find
It returns an index, why would you insert an index into the state?
The answer partially came from yourfavoritedev.
As he said you can use the built-in Array.prototype.map() and do it like this:
handleSortUp = (moduleid ,newOrder) => {
const { modules } = this.state.activity;
const newModules = modules.map(module => module.module_id === moduleid ? { ...module, order: newOrder } : module)
this.setState({ activity: { ...this.state.activity, modules: newModules } });
}
This should work, let me know but I strongly advice to ask me or search on the web if you don't understand what is happening there (syntactically or semantically speaking).

Searching for data in arrays [Node.JS]

I have a question:
(sorry for the bad formatting)
I have an array:
[
{
"data": [
[
"kek",
"lol"
],
[
"notkek",
"notlol"
]
]
}
]
If someone writes "kek" it should search it in the "data" array and return the "kek" position inside its array
(["kek","lol"])
and its array position
{
"data": [
[
"kek",
"lol"
]}
(in this case "data[0]")
If anybody knows the answer, please help me
The method Array.findIndex and Array.includes may help you
const obj = {
data: [
[
'kek',
'lol'
],
[
'notkek',
'notlol'
],
],
};
const keyToSearch = 'kek';
// We look for the key
const index = obj.data.findIndex(x => x.includes(keyToSearch));
if (index === -1) {
console.log(`We didn't found ${keyToSearch}`);
} else {
console.log(`We found ${keyToSearch} at index ${index}`);
}
Double index recuperation
const obj = {
data: [
[
'kek',
'lol'
],
[
'notkek',
'notlol'
],
[
'notkek',
'notlol',
'otherstuff',
'kek',
'test',
],
],
};
const keyToSearch = 'kek';
const ret = obj.data.reduce((tmp, x, xi) => {
// We look for the key
const index = x.findIndex(y => y === keyToSearch);
if (index === -1) return tmp;
return [
...tmp,
{
absoluteIndex: xi,
relativeIndex: index,
},
];
}, []);
if (!ret.length) {
console.log(`We didn't found ${keyToSearch}`);
} else {
ret.forEach(({
absoluteIndex,
relativeIndex,
}) => console.log(
`We found ${keyToSearch} at`,
`data index ${absoluteIndex}, in ${relativeIndex} position`,
));
}
userInput = 'kek'
let item = data.map((item, indx) => {
item.includes(userInput) ? return({"indx":indx,"nestedIndex":item.indexOf(userInput)}) : null
})
map over the data array and if the nested array had the item your searching for than return the index of the array and the index of the item with in that array

"$or needs an array" on a request where $or is an array

I try to implement a $or query in mongodb but got the error: $or needs an array.
Here is my request:
const filters = {
"$or": [
{
"positionStatus": {
"$in": [
"trainee"
]
}
},
{
"positionStatus": {
"$exists": false
}
},
{
"positionStatus": []
},
{
"positionStatus": [
""
]
}
]
}
I tested the type of the $or attribute of my object with Array.isArray and it returns true:
console.log('is array: ', Array.isArray(filters['$or']));
I use the version 2.2.33 of the Nodejs driver and Mongorito.
const items = yield Item
.sort(formatted_sort)
.find(filters)
.map(item => ...);
Edit
After investigating a bit more, it appears the problem is when using the expression with count:
const count = yield Sentence
.where(filters).count();
Thanks for your help!

Resources