I try to insert a string into a particular index of object if condition is true inside a forloop but its not inserting of some reason. I tried to use push and append and splice but splice just inserting entire string as an new object into the array and i need it to just append to existing object. Any ideas how to make it work?
Data looks like that:
const [concerts, setConcerts] = useState([]);
const [tickets, setTickets] = useState([]);
const [limit, setLimit] = useState(25);
const navigate = useNavigate();
const [button, setButton] = useState(false);
const [array, setArray] = useState([]);
//Raw JSON Date example: "2023-02-08T23:15:30.000Z"
let currentDate = new Date().toJSON().slice(0, 10);
const json = { available: "true" };
useEffect(() => {
const loadConcerts = async () => {
const resConcerts = await axios.get("/data/concerts");
const resTickets = await axios.get("/data/tickets");
let table = [];
setTickets(resTickets.data);
// getting all concerts above today
const filteredData = resConcerts.data.filter((concert) => {
return concert.datum >= currentDate;
});
filteredData.forEach((element) => {
table.push(element);
// table.splice(10, 0, { status: "available" });
});
setArray(table);
for (let i = 0; i < resTickets.data.length; i++) {
for (let j = 0; j < filteredData.length; j++) {
if (
resTickets.data[i].concertid == filteredData[j].id &&
resTickets.data[i].booked == 0
) {
table.push({ status: "avaiable" });
// table.splice(10, 0, { status: "available" });
}
}
}
setArray(table);
// filteredData.forEach((concert) => {
// for (const ticket of tickets) {
// if (concert.id == ticket.concertid && ticket.booked == 0) {
// table.push(json);
// }
// }
// });
setConcerts(
filteredData.sort((a, b) =>
a.datum > b.datum ? 1 : a.datum < b.datum ? -1 : 0
)
);
};
console.log("from use effect: " + array.length);
loadConcerts();
}, []);
After using splice method:
Update
Problem is solved. I used Object.assign() helped to append string to existing object in array. Actually i had to insert another object, not a single variable.
The problem is you are trying to push a string "available" into an array-of-objects.
Here you see the object with a property datum:
const filteredData = resConcerts.data.filter((concert) => {
return concert.datum >= currentDate;
});
Yet below when you push, you are not pushing an object into the array which is problematic. It should probably be something like this but you have to verify:
Instead of this:
filteredData.push("available");
Domething like this:
filteredData.push({ datum: '', status: 'available' );
I don't know what your data object is but it's an object not a string you need to add to that array.
The looping twice is likely from React 18 New Strict Mode Behaviors. It intentionally unmounts/remounts components to fire your useEffect calls twice - so that you can identify problematic side effects. If you remove <StrictMode> or run in production that double-looping should not occur.
Problem solved. Push() neither splice() method didn't helped. What helped me to append my object to another object without changing the data was Object.assign() function
for (let i = 0; i < resTickets.data.length; i++) {
for (let j = 0; j < filteredData.length; j++) {
if (
resTickets.data[i].concertid == filteredData[j].id &&
resTickets.data[i].booked == 0
) {
Object.assign(filteredData[j], obj);
}
}
}
For example i am having an array of data as below
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]
i need to list the same data as below in javascript
var arrDataSorted = ["40-25","50-48","30-25","40-23","40-45","40-50","40-50"]
need only the common data that replicates also the null to be removed.
What is the best solution to solve this.
You can try using Array.prototype.filter() to remove null values and Set to get the unique values. Finally use the Spread syntax (...) to transform the set result into an array.
Try the following way:
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
var arrDataSorted = [...new Set(arrData.filter(i => i))];
console.log(arrDataSorted);
You can create a set from an array which will automatically remove duplicates:
let arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
let set = new Set(arrData);
This will still keep the null, which you can remove with a delete call, and convert back to array with the spread ... operator. The final code will be:
let set = new Set(arrData);
set.delete(null);
let distinctArr = [...set];
add the values into the set if the value is not null and convert it to array.
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
var setData = new Set();
for(var data of arrData) {
if(data) {
setData.add(data);
}
}
var arrDataSorted = [...setData];
console.log(arrDataSorted);
Add this function to your code:
function removeCommonValues(arr) {
let result = [];
for(let i=0; i < arr.length-1; ++i) {
if(result.includes(arr[i]) === false && arr[i] !== null)
result.push(arr[i])
}
return result
}
Usage:
removeCommonValues(["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]) // Return ["40-25", "50-48", "30-25", "40-23", "40-45", "40-50"]
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]
var set = new Set();
for ( var i = 0 ; i< arrData.length;i++ ) {
if(arrData[i]!==null) {
set.add(arrData[i]);
}
}
var newArr = [...set]
You could use array built-in reducer method, in the next code i'm starting with an empty array, and i'm only returning the items that are not null and are not already in the array.
const data = arrData.reduce((state, value) => {
if(value && !state.includes(value)) {
return [...state, value];
}
return state;
}, [])
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]
const output = [];
arrData.forEach(val => {
if(output.indexOf(val) === -1 && val !== null) {
output.push(val);
}
});
console.log(output);
The function can be in a separated file to be reused between multiple pages. Then you can call that function to filter distinct values that are not null.
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
function fn(value,index,self){
return self.indexOf(value) === index && value;
}
console.log(arrData.filter(fn));
I have a string like this:
let user = "req.user.role"
is there any way to convert this as nested objects for using in another value like this?
let converted_string = req.user.role
I know I can split the user with user.split(".")
my imagination :
let user = "req.user.role".split(".")
let converted_string = user[0].user[1].user[2]
I found the nearest answer related to my question : Create nested object from query string in Javascript
Try this
let user = "req.user.role";
let userObj = user.split('.').reduceRight((obj, next) => ({
[next]: obj
}), {});
console.log(userObj);
Or this, for old browsers
var user = "req.user.role";
var userArray = user.split('.'), userObj = {}, temp = userObj;
for (var i = 0; i < userArray.length; i++) {
temp = temp[userArray[i]] = {};
}
console.log(userObj);
The function getvalue() will return the nested property of a given global variable:
var user="req.user.role";
var req={user:{role:"admin"}};
function getvalue(str){
return str.split('.').reduce((r,c,i)=>i?r[c]:window[c], '');
}
console.log(getvalue(user));
I'll take my shot at this:
let user = "req.user.role"
const trav = (str, o) => {
const m = str.split('.')
let res = undefined
let i = 0
while (i < m.length) {
res = (res || o)[m[i]]
if (!res) break
i++
}
return res
}
const val = trav(user, {
req: {
user: {
role: "admin"
}
}
})
console.log(val)
this function will traversed the passed in object for the entire length of the provided string.split "." list returning either a value or undefined.
You can do it like this:
let userSplitted = "req.user.role".split('.');
let obj, o = obj = {};
userSplitted.forEach(key=>{o=o[key]={}});
Here is my requirement. I was able to achieve to some level in java but we need to move it to typescript (client side).
Note: The below input is for example purpose and may vary dynamically.
Input
var input = ["a.name", "a.type", "b.city.name" , "b.city.zip", "b.desc","c"];
We need to create an utility function that takes above input and returns output as below.
Output:
Should be string not an object or anything else.
"{ a { name, type }, b { city {name, zip } , desc }, c }"
any help is much appreciated.
I don't see that typescript plays any role in your question, but here's a solution for constructing the string you requested. I first turn the array into an object with those properties, then have a function which can turn an object into a string formatted like you have
const input = ["a.name", "a.type", "b.city.name" , "b.city.zip", "b.desc","c"];
const arrayToObject = (arr) => {
return arr.reduce((result, val) => {
const path = val.split('.');
let obj = result;
path.forEach(key => {
obj[key] = obj[key] || {};
obj = obj[key];
});
return result;
}, {});
}
const objectToString = (obj, name = '') => {
const keys = Object.keys(obj);
if (keys.length === 0) {
return name;
}
return `${name} { ${keys.map(k => objectToString(obj[k], k)).join(', ')} }`;
}
const arrayToString = arr => objectToString(arrayToObject(arr));
console.log(arrayToString(input));
Here's another variation. Trick is to parse the strings recursively and store the intermediate results in an Object.
function dotStringToObject(remainder, parent) {
if (remainder.indexOf('.') === -1) {
return parent[remainder] = true
} else {
var subs = remainder.split('.');
dotStringToObject(subs.slice(1).join('.'), (parent[subs[0]] || (parent[subs[0]] = {})))
}
}
var output = {};
["a.name", "a.type", "b.city.name" , "b.city.zip", "b.desc","c"].forEach(function(entry) {
dotStringToObject(entry, output)
});
var res = JSON.stringify(output).replace(/\"/gi, ' ').replace(/\:|true/gi, '').replace(/\s,\s/gi, ', ');
console.log(res)
// Prints: { a { name, type }, b { city { name, zip }, desc }, c }
You could do something like this:
var input = ["a.name", "a.type", "b.city.name" , "b.city.zip", "b.desc","c"];
var output = {};
for(var i =0; i < input.length; i+=2){
output[String.fromCharCode(i+97)] = {};
output[String.fromCharCode(i+97)].name = input[i];
output[String.fromCharCode(i+97)].type = input[i+1];
}
console.log(JSON.stringify(output));
I have 2 JSON files: A which is on a remote server, and B which is in local storage.
I'd like, on page load, for jQuery to compare both files and, if an object is in the B file, but not in A, for the object to be removed from local storage.
var fileA = '[{"ID":"1","foo":"bar"},{"ID":"3","foo":"bar"}]'; //Remote file
var fileB = '[{"ID":"2","foo":"bar"},{"ID":"3","foo":"bar"}]'; //localStorage
var jsonA = JSON.parse(fileA);
var jsonB = JSON.parse(fileB);
jsonA.forEach(function(allA) {
jsonB.forEach(function(allB) {
if (allA.ID != allB.ID) {
var i = jsonB.findIndex(mydata => mydata.ID === allA.ID);
if (i !== -1) {
jsonB.splice(i, 1);
if (jsonB.length === 0) {}
localStorage.setItem('panier', JSON.stringify(jsonB));
}
}
})
})
What I'm trying to do is delete ID:2 from local storage because it's not in A.
Check this code below:
Tips: Avoid using nested forEach loop to increase efficiency.
var fileA = '[{"ID":"1","foo":"bar"},{"ID":"3","foo":"bar"}]';//Remote file
var fileB = '[{"ID":"2","foo":"bar"},{"ID":"3","foo":"bar"}]'; //localStorage
var jsonA = JSON.parse(fileA);
var jsonB = JSON.parse(fileB);
// Temporary array to hold all id in file a
var arrA = [];
//Push all id in file A to arrA
jsonA.forEach(a => {
arrA.push(a.ID);
});
jsonB.forEach((b,index) => {
// check if arrA has b.ID
if (arrA.indexOf(b.ID) == -1){
jsonB.splice(index,1)
}
})
console.log(jsonB)
localStorage.setItem('panier', JSON.stringify(jsonB));
Try the following:
var fileA = '[{"ID":"1","foo":"bar"},{"ID":"3","foo":"bar"}]';//Remote file
var fileB = '[{"ID":"2","foo":"bar"},{"ID":"3","foo":"bar"}]'; //localStorage
var jsonA = JSON.parse(fileA);
var jsonB = JSON.parse(fileB);
jsonB = jsonB.filter((o) => jsonA.findIndex((obj)=> obj.ID === o.ID)!=-1 );
console.log(jsonB);