How to get array out of object in JS [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I was trying to get data from the notes array in the data object. I'm getting the object from mongodb and I want to get the array called notes. but I can't do it. for some reason. In java there is like Object.get(notes) and I can get a specific field within the object but I don't know how to do that in js. And I haven't been able to find something that works elsewhere online.
here is my code
axios.post('/api/user/notes')
.then(res => {
console.log( Object.values(res.data));
dataSet = Object.values(res.data);
console.log(dataSet[0]);
console.log(dataSet.notes[0]);
}).catch(err => {
console.log('it didnt work' + err);
});
image

dataSet is an array. So, to get the notes, you have to first select the first element of data, dataSet[0] and then the notes array. To get the first note, it would be dataSet[0].notes[0]. Also, beware that you are setting a global variable (perhaps on a browser's window object) when you type dataSet = ... What you probably want is to declare a variable local to the function with var dataSet = ...

Related

Cannot create a new object and assign new values using spread operator [duplicate]

This question already has answers here:
How to clone File objects in javascript?
(3 answers)
How to get all properties of a File Object in javascript?
(1 answer)
How to create a modified copy of a File object in JavaScript?
(3 answers)
Closed last month.
So i tried to create a new object as a solution for an issue that I had in my code. But when I tried to create a new object with the updated values it doesn't return the old values. just the updated value. what could be the issue?
Had to create a new object instead of modifying the existing one because some values are read only.
Here is the function that check for duplicate files,
const beforeUpload = (event: any) => {
const file: any = event?.target?.files[0];
const duplicateFile= fileList.find((files)=>{
return files.name==file?.name;
})
if(duplicateFile){
console.log(duplicateFile);
const updatedFile={
...duplicateFile,
name:`${duplicateFile.name}(${duplicateCount})`
};
console.log(updatedFile);
setDuplicateCount(duplicateCount+1);
}
if (!file) {
return;
}
takes a file and checks whether the file name already exists or not. And add a number to the end of the file name. i want to create a new object with the update name. Thats where I get the issue.
Here is the console output,
The object on the top is what function receiving and the bottom one is the output. TIA.

How do I assign a variable array name to be used in a foreach loop using javascript? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 months ago.
I have a script which receives a JSON formatted file as input and allows the user to call out a JSON object name for specific processing. I loop through the JSON file using a foreach() to process the specific items requested by the end user.
In this example The JSON input file has an object array called "socks". The requested JSON object name could be input by the user as "socks" as this would be the object they would like to have the code perform a function on.
I push all of these "socks" to a new array to perform the work on.
//working code
jsonDataIn.socks.forEach(function(s) {
newArray.push({ socks:s })
});
The above code functions as needed because I have hardcoded the array name as 'socks'. I cannot figure out how to assign the array name as a variable to apply the users input.
//I'd tried assigning just the array name as a variable, as well as both the data and array and those both are not valid.
let inputValueFromUser = 'socks';
let arrayNameVar=jsonDataIn.inputValueFromUser;
arrayNameVar.forEach(function(s) {
newArray.push({ [inputValueFromUser]:s })
});
nor this
let inputValueFromUser = 'socks';
let arrayNameVar=inputValueFromUser;
jsonDataIn.arrayNameVar.forEach(function(s) {
newArray.push({ [inputValueFromUser]:s })
});
In the above code the [inputValueFromUser] works for assigning the value to the newArray, but I cannot figure out how to get it to work inline as a form of 'jsonDataIn.inputValueFromUser.forEach()'. I found many examples if I were using multiple arrays in a forEach loop, but not how to pass the 'inputValueFromUser' as an array name.
I know it has to be a simple solution that I'm missing. Any assistance is appreciated.
All of the failed code that I've tried to make work has resulted in "TypeError: Cannot read properties of undefined (reading 'forEach')"

How do I access a specific element in an Object? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I am having a hard time trying to accessing any elements in my object.
Find below my code that accesses the object from the localStorage and prints it out on the browser console:
var test = localStorage.getItem('transactionData');
console.log(test);
The above code yields:
[{Amount":"15,000","payersNumber":"070505788","waitersName":"Agnes"}]
When I try to access the element waitersName as seen in the code below:
console.log(">> " +test.waitersName);
It yields:
>> undefined
How do I access the various elements in my object?
test is an array with an object in it, you'll need to access the array item first with test[0] and that will return the object, which will then allow you to access its properties.
The data you retrieve from localstorage is a stringified version of the Javascript array. You first have to parse it using
var array = JSON.parse(test);
Then get your elements from the parsed array.

Unable to access an array where the contents of said array are visible in Console.Log [duplicate]

This question already has answers here:
How can I make console.log show the current state of an object?
(12 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I setup a global variable to hold the data array:
var data = [];
This is a global variable as it is used outside of a function and needs to be accessible for all functions
I then iterate over a data set and populate the data array.
When I access this array using the console:
console.log(window.data);
I can see the following in Chromes console view:
There are many more records in the data set, they all follow exactly the same format
The issue I am having is, I cannot access this data array and am seeing zero length as shown below:.
console.log(window.data.length); // returns 0
I'm not clear on why this is occurring and am hoping someone can point out what I am doing wrong.
It seems like the result of processing this array is not available at the time I am trying to get the length, therefore I am getting zero.
Have tried the following at the end of the html file:
$( document ).ready(function() {
console.log("ready!"); // returns ready!
console.log(window.data[15]); // returns undefined
});
Not quite sure how to proceed, so any advice would be very welcome.
EDIT:
This was resolved by the use of promises (bottom link in the duplicate notice above).
Previous code was removed as it didn't add to the discussion and would probably only create confusion
Core issue was based on data not being available on page load due to processing of large arrays.

Access object using dynamic object name [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
I have an object with some data inside. The first level of data are 2 arrays (body, cause). Each body and cause array have arrays inside of them (date, year).
totals:[{body:[
{date:[54,9,3,17]},
{year:[437,61,31,140]}]},
{cause:[
{date:[54,9,3,17]},
{year:[437,61,31,140]}]
}]
What I would like to do is access the body/cause array dynamically based on something the user has changed.
This is how I am accessing them now.
totals[isCause].body[isYear].date[filterNumber]);
My issues is body and date are hard coded in there, and I would like to have access to either body/cause date/year. I can't seem to find what these property names are stored as. I tried to set up a var and do something like this
var bodyCause = "body";
Then I tried to pass it back into my retriever statement.
totals[isCause].bodyCause[isYear].date[filterNumber]);
But that fails. So I'm just trying to figure out what that property name is stored as and if I can dynamically set it when I need to retrieve information.
Your attempt was almost correct. You can easyly use var bodyCause = "body"; and access the content dynamically. Instead of this
totals[isCause].bodyCause[isYear].date[filterNumber]);
you should use this
totals[isCause][bodyCause][isYear].date[filterNumber]);
Should fix your problem.

Categories