How to access values inside a multiple array JSON object? - javascript

How can I access array data inside my json object data?
const [data, setData] = useState([])
const getData = () => {
axiosInstance
.get(url + slug)
.then(result => setData(result.data))
}
useEffect(() => {
getData()
}, [])
Here are something I've tried:
console.log(data['symbol'])
console.log(data[0]['symbol'])
console.log(data[0].symbol)
Here is the data being used in my state:
To keep it simple, lets say I want to the access first array, and console log all values for symbol. How would I go about doing that?

Your object data looks like an array of arrays of objects.
This should work:
data[0][0].symbol
To log all the symbols of the first array:
console.log(data[0].map(item => item.symbol))

To access the first array you can use this data[0] to map through all the objects inside the first array and log them you do the following
data[0].map(item => console.log(item.symbol))

Related

Convert incoming string to dictionary/map javascript

I am new javascript. I could do this in 2 seconds in python/java but I am struggling here. I am developing an reactJS app. I am retrieving a string which is a dictionary/HashMap<String, ArrayList> from a server via axios. I get response.data and my data is in the form:
{ "key1": [1,23,4,5,5,2],
"key2": [2,6,5,5,5,6,5],
...
}
I want to convert this into a map/dictionary so I can access it like so (get(), keys(), etc.
However, i am having trouble doing this.
console.log(typeof data) gives me string.
And when I JSON.parse() or JSON.stringify() and use new Map() i get this weird thing with thousands of integer keys and it doesn't act like I want. Any idea on how I can do this?
Thanks!
EDIT
Here is a more complete code example.
const fetchData = () => {
const url = "http://127.0.0.1:8081/pdata";
const promise = axios.get(url);
console.log(promise);
const dataPromise = promise.then((response) => response.data);
console.log(dataPromise);
return dataPromise;
}
export default function Home() {
//Bind the data to a useState Hook in React, to ensure that we have the correct data
const [data, setData] = React.useState([]);
//This function runs on page reload, twice. Your fetch data function will run repeatedly while contained
//within this functional component.
useEffect(() => {
fetchData().then((apiEndpoint) => {
//setting data equal to the result of the FetchData function
setData(apiEndpoint);
}).catch(err => console.log(err))
}, [])
// We now have the data.
// Convert it to a map
const map = new Map(Object.entries(data));
console.log(map.get("Model Used"));
console.log([...map.keys()]);
At point We now have the data, console.log(data) prints the incoming data correctly its just is of type string not map or whatever javascript calls it.
Using Map and Object#entries:
const obj = { "key1": [1,23,4,5,5,2], "key2": [2,6,5,5,5,6,5] };
const map = new Map(Object.entries(obj));
console.log(map.get("key1"));
console.log([...map.keys()]);
From https://flexiple.com/javascript/javascript-dictionary/
Are there dictionaries in JavaScript? No, as of now JavaScript does not include a native “Dictionary” data type. However, Objects in JavaScript are quite flexible and can be used to create key-value pairs. These objects are quite similar to dictionaries and work alike.
It seems you can just parse the string that you obtained to JSON and use the parsed object obtained. For example:
var api_response = `
{
"key1": [1,23,4,5,5,2],
"key2": [2,6,5,5,5,6,5]
}`;
var parsed_data = JSON.parse(api_response);
console.log(Object.keys(parsed_data))
console.log(parsed_data["key2"])
console.log(parsed_data.key1)

Unwanted modification in State variable (Hook), due to manipulation of local variable

import React, { useState, useEffect } from "react";
export const Test = () => {
const [data, setData] = useState([]);
const file = [{ id: 1, description: "Test Data" }];
useEffect(() => setData(file), []);
const manipulateData = (data) => {
let tempArray = [...data];
tempArray.map((item) => delete item.id);
};
return (
<>
<h1>Testing Data</h1>
{manipulateData(data)}
{console.log(data)}
</>
);
};
I want to make modification to the local variable "tempArray", and the changes shall not reflect in the variable "data"
This happens because you are creating a new array, but the objects in that array are not deeply copied. Instead, they represent just a reference to the very same objects as in data.
Because both references are pointing at the same object, if you delete an object property from the tempArray objects, you are actually deleting it from the data objects.
If you want to solve this, you have to destroy the reference by making a deep copy of the objects from the data array.
Here is an example how to do it:
export const Test = () => {
const [data, setData] = useState([{ id: 1, description: "Test Data" }]);
const manipulateData = (data) => {
let tempArray = data.map((item) => {item.description}); //this will create an array with new object, and destroy the reference to the objects of data.
};
return (
<>
<h1>Testing Data</h1>
{manipulateData(data)}
{console.log(data)}
</>
);
};
Also, instead of deleting a property, better pick the one that you need.
The following code:
let tempArray = [...data];
only shallow copies your data array, meaning that any of the objects inside of tempArray refer to the same objects in memory that are within the data array. This means that when you loop over your objects with .map(), each item refers to an object from data as well, which results in the objects in data changing when you use delete item.id.
Currently, you are using .map() just to loop over your tempArray, this isn't the purpose of .map(). The .map() method returns a new array, and the callback function you pass it should return a new value that you want to map the current value to. This means you can use .map() to create tempArray, by making the callback function return a new object that excludes the id property:
const manipulateData = (data) => {
const tempArray = data.map(({id, ...rest}) => rest);
// ... do what you need with `tempArray` ...
};
Above, {id, ...rest} is destructuring assignment syntax, which extracts the id property from the current element, and stores all other properties/values from the current object in rest. This allows you to create a new object that excludes the id property.
As a side note, you shouldn't be calling methods such as console.log() and manipulateData() inside of JSX if they don't return anything meaningful that will be rendered to the screen, instead, you can put these in a useEffect() hook.
const [data, setData] = useState([{ id: 1, description: "Test Data" }]);
try this
Your way is right in case you are not using a multi-dimensional array, but here you are cloning a multi-dimensional array,
and by using the = operator, it’ll assign objects/arrays by reference instead of by value! That means whenever you modify any of the two objects it's going to affect the value in both.
A good way to solve this is by creating a deep clone by doing something like this
const tempArray = JSON.parse(JSON.stringify([...data]))
tempArray.map((item) => delete item.id)

Getting elements form object [1] and place it all on object [0] javascript

So I have a payload that pushes firestore collection to an object. Currently when I console.log the object, it shows:
I need it to be in just 1 array, how do I go about that?
I need it to look like (image below) so I can use it with my vuetify data tables
My vuex goes like this:
mutations: {
firebaseOrders(state, payload) {
state.firebaseOrders.unshift(payload)
},
actions: {
getFireBaseOrders(state) {
db.collection("orders").onSnapshot((res) => {
const changes = res.docChanges();
changes.forEach((change) => {
// Push all data to firebaseOrders[]
let payload = change.doc.data();
state.commit("firebaseOrders", payload);
...
This joins the two arrays together.
new_array = old_array[0].concat(old_array[1])
Reference: MDN Web Docs

How to merge values inside stateless component?

Updating a state variable always replaces it instead of merging it. How can I merge it? Function addFruits receives multiple objects like:
{fruitName: banana} {fruitName: apple} {fruitName: watermelon}
How to push this fruitName's into fruits state?
My code returns only the last fruitName. But how to merge all fruitNames like array.push(val);
const [fruits, setFruits] = useState([]); // this is the state
function addFruits(value){
Api.get(`${PATH.GET_SELECTED_FRUITS}/${value}/fruits`).then(res => { // this method gives me multiple object, (like {fruitName: banana} {fruitName: apple} {fruitName: watermelon})
res.map(result => {
setProps(result.fruitName);
})
})
}
You need to combine the existing fruits array with the result from the API:
.then((res) => {
setFruits([
...fruits,
...res.map(fruit => fruit.fruitName)
]);
});
You can merge the response with the state -
function addFruits(value){
Api.get(`${PATH.GET_SELECTED_FRUITS}/${value}/fruits`).then(response => {
totalFruits = [...fruits,
...response.map(fruit => fruit.fruitName)]
setFruits(totalFruits);
})
})

Convert object to array in Javascript / React

Using REST, I am retrieving an object(JSON format) which is to be converted to an array so that it can be inserted into a table.
This is done in the rendering function of React.
The input is updated every N minutes from the back-end.
How do I convert an object to an array?
I need only the values, not the keys, since the keys are already present as column values beforehand in the table itself.
You can use Object#values (ECMAScript 2017), but it's not supported by IE (see browser's compatibility).
Note: The ECMAScript 6 specification defines in which order the properties of an object should be traversed. This blog post explains the details.
const map = { a: 1, b: 2, c: 3 };
const result = Object.values(map);
console.log(result);
If you need to support IE, you can use Object#keys with Array#map:
const map = { a: 1, b: 2, c: 3 };
const result = Object.keys(map).map((key) => map[key]);
console.log(result);
I am not sure by map you mean the Map object or an ordinary JS object. However, just for variety I would like to mention that the Map objects are mostly (probably always) stringified like JSON.stringify([...myMap]). So if you happen to receive a Map object in JSON data may be you should do something like;
var myMap = new Map().set(1,"hey").set(2,"you"),
mapData = JSON.stringify([...myMap]),
values = JSON.parse(mapData).map(d => d[1]);
console.log("mapData:",mapData);
console.log("values:",values);
You can set initial value as array firstly. See this example:
const [conversations, setConversations] = useState([]); // fianal data is array
useEffect(() => {
const fetchConversations = async () => {
const res = await axios.get("/conversations/" + user._id);
setConversations(res.data);
};
fetchConversations();
}, [user._id]);
res.data convert to array by using useState([]) as initial value and convert to object by using useState({}).
And
return(
{conversations.map((conv) => (
))}
)
You can set initial value as array firstly. See this example:
const [conversations, setConversations] = useState([]); // fianal data is array
useEffect(() => {
const fetchConversations = async () => {
const res = await axios.get("/conversations/" + user._id);
setConversations(res.data);
};
fetchConversations();
}, [user._id]);
res.data convert to array by using useState([]) as initial value and convert to object by using useState({}).
And map this array:
return (
<>
{conversations.map((conv) =>
(<Conversations key={conv._id} conversation={conv} />))}
</>
)

Categories

Resources