Accessing value in nested object [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I don't understand how I can access an value in a object that is an array with an object inside itself.
I've tried with the dot notation and [] and array.reduce. But I'm doing something wrong.
I've changed the values but the structure remains the same:
"test": {
"title": "My title",
"category": null,
"info": [{
"time": 10,
"type": "minutes"
}]
}
I need to get the values of time and type, but I get undefined.

The final object is first element of array so you need to first access its first element.
const obj = {
"test": {
"title": "My title",
"category": null,
"info": [{
"time": 10,
"type": "minutes"
}]
}
}
console.log(obj.test.info[0].time);
console.log(obj.test.info[0].type);

Use the dot notation to access the properties
Object a consists of the test object which in-turn contains the key info whose value is an array containing one object with the required keys
a->test->info->[{time,type}]
var a = {
"test": {
"title": "My title",
"category": null,
"info": [{
"time": 10,
"type": "minutes"
}]
}
}
console.log(a.test.info[0].time)
console.log(a.test.info[0].type)

Related

how to add elements to array using push [duplicate]

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 1 year ago.
Having issues with array data
OUT PUTTING LIKE THIS
[{
"createdAt": [Object],
"date": "2021-08-22",
"description": "Yes"
}, {
"title": "greatt"
}
I need it to output like this below
[{
"createdAt": [Object],
"date": "2021-08-22",
"description": "Yes",
"title": "greatt"
}
const myList = [];
myList.push(otherArray, {title: 'Hello'})
The result you're getting indicates that otherArray is not an array, it's a single object
{
"createdAt": [Object],
"date": "2021-08-22",
"description": "Yes"
}
So you're pushing two separate objects onto myList.
If you want to merge an object into another object, you can use Object.assign().
Object.assign(otherArray, {title: 'Hello'});
Then you can do
myList.push(otherArray);
to add that object to the myList array.
I think what you want to do is push the extra object values inside the last object of the array ! So here's the solution for that =>
let array = [{
"createdAt": [Object],
"date": "2021-08-22",
"description": "Yes"
}]
function push(props , array) {
let lastIndex = array.length - 1;
array[lastIndex] = Object.assign(props, array[lastIndex]);
}
push({
title: "Title"
}, array);
console.log(array)
For more information about Object.assign checkout MDN

Taking contents of an array of objects, and assigning them to a property on a JSON object

I want to take items from this array (the way I save things on the client)
[
{
"id": "-Mdawqllf_-BaW63gMMM",
"text": "Finish the backend[1]",
"status": true,
"time": 1625248047800
},
{
"id": "-Mdawqllf_-BaW63gGHf",
"text": "Finish the middle-end[2]",
"status": false,
"time": 1625248040000
},
{
"id": "-Mdawqllf_-BaW63gGHd",
"text": "Finish the front-end[3]",
"status": false,
"time": 1625248040000
}
]
And turn them into this format for how I save it server side
{ "todos": {
"-Mdawqllf_-BaW63gMMM": {
"text": "Finish the backend[1]",
"status": true,
"time": 1625248047800,
},
"-Mdawqllf_-BaW63gGHf": {
"text": "Finish the middle-end[2]",
"status": false,
"time": 1625248040000,
},
"-Mdawqllf_-BaW63gGHd": {
"text": "Finish the front-end[3]",
"status": false,
"time": 1625248040000,
}
},
}
Basically i turn items into an array on the client to help with sorting and making use of arrays. But before sending it back need to put into the right format
Use .map() to loop over the array of objects to exctract the id property, so you can use it as the key of the new object.
Use Object.fromEntries() to create the new object from the array returned by .map().
const data = [
{
"id": "-Mdawqllf_-BaW63gMMM",
"text": "Finish the backend[1]",
"status": true,
"time": 1625248047800
},
{
"id": "-Mdawqllf_-BaW63gGHf",
"text": "Finish the middle-end[2]",
"status": false,
"time": 1625248040000
},
{
"id": "-Mdawqllf_-BaW63gGHd",
"text": "Finish the front-end[3]",
"status": false,
"time": 1625248040000
}
];
const todos = {
Todos: Object.fromEntries(data.map(obj => [obj.id, obj]))
};
console.log(todos);
#Barmar's solutions is nice.
For the sake of learning or others googling. You can also reduce the array to an object.
const todos = data.reduce((obj, item) => {
obj[item.id] = item
return obj
}, {})
const items = {
todos: {
...data
}
};
Assume that data is the array of objects.
Use the spread operator to copy all the array objects from data array to the todos object at key todos.
One important thing to note that you can't assign more than one objects without array to a single object key. You definately have to use the array to maintain all the objects under the one key.
Avoid using the hardcode index. Always use the spread operator

traversing JSON using a variable [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 trying to traverse a JSON file using a variable that gets set earlier in my script.
Example of the JSON:
{
"page1": [{
"template": "temp1",
"other": "example"
}],
"page2": [{
"template": "temp2",
"other": "example"
}],
"page3": [{
"template": "temp3",
"other": "example"
}]
}
The variable can be one of three items... page1, page2, page3
As I said I am setting the variable further up in the code so say the variable is:
var getid = "page1";
What I want to do is, if the variable is "page1", then get the "template" value of "temp1".
my console.log
console.log(json[getid]);
returns
[{template: "temp1"}]
but I don't really know how to go any further. Everything I try returns "undefined" or an error.
As I said, I want to get "temp1" in this example.
Can anyone help me along?
If you need more info, please let me know.
Thanks,
var json = {
"page1": [{
"template": "temp1",
"other": "example"
}],
"page2": [{
"template": "temp2",
"other": "example"
}],
"page3": [{
"template": "temp3",
"other": "example"
}]
};
var getid = "page1";
console.log(json[getid][0].template);
you are very close to the solution, just access object inside array you are done.
json[getid][0].template
will do
You can use the code below. json[getid] return an array of one object So you need to access the first item of array using [0] which will return object object and then use .template
let json = {
"page1": [{
"template": "temp1",
"other": "example"
}],
"page2": [{
"template": "temp2",
"other": "example"
}],
"page3": [{
"template": "temp3",
"other": "example"
}]
}
var getid = "page1";
console.log(json[getid][0].template);

Retrieve value from object having key and index as a string: 'array[0].key' [duplicate]

This question already has answers here:
Access a nested property with a string [duplicate]
(5 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 4 years ago.
I'm working with some specific library for forms in javascript. In this library if I have:
{
"id": 1,
"order": 0,
"title": "A title",
},
I can do:
const field = 'order';
form.getState().values[field]
And I'll get the title value.
Now let's say that I have this data:
{
"id": 1,
"order": 0,
"title": "A title",
"Tags": [
{
"id": 1,
"name": "Tag one",
},
{
"id": 2,
"name": "Tag two",
}
]
},
And also I have access to a string with the name of the field for tags, the index of the array, and the field I want to retrieve. But I have all this in a string:
Tags[0].name
If I do:
const field = 'Tags[0].name';
form.getState().values[field]
It will return undefined, because will try to find the key Tags[0].name in the object. So: how can I do to retrieve the name property from a specific index in the Tags array, having Tags[0].name as a string?
A bit nasty but quick and working way to do it is to use eval:
const field = 'Tags[0].name';
let stateValues = form.getState().values;
let tagName = eval(`stateValues.${ field }`)
Other approach might be to split and parse the field path using regexp and then traverse the object property by property.

javascript object variable with # sign [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 8 years ago.
i'm trying to pull some data from last.fm.
i get the following reply:
{
"tracks": {
"track": [
{
"name": "Once Upon a Dream",
"duration": "203",
"loves": "738",
"mbid": "92078817-2e04-4bcd-9c43-ebb9c2d1823c",
"url": "http://www.last.fm/music/Lana+Del+Rey/_/Once+Upon+a+Dream",
"streamable": {
"#text": "0",
"fulltrack": "0"
},
"artist": {
"name": "Lana Del Rey",
"mbid": "b7539c32-53e7-4908-bda3-81449c367da6",
"url": "http://www.last.fm/music/Lana+Del+Rey"
},
"image": [
{
"#text": "http://userserve-ak.last.fm/serve/34s/96432461.png",
"size": "small"
},
{
"#text": "http://userserve-ak.last.fm/serve/64s/96432461.png",
"size": "medium"
},
{
"#text": "http://userserve-ak.last.fm/serve/126/96432461.png",
"size": "large"
},
{
"#text": "http://userserve-ak.last.fm/serve/300x300/96432461.png",
"size": "extralarge"
}
]
}
And so on...
The problem lies when trying to access the image portion of the reply, the image object seems to have #text as variable name of the info i'm trying to access. a normal response.tracks.track[i].image[0].text obviously doesn't work.
is there some special way to access this variable ?
You can use the square bracket notation to access that variable like so:
response.tracks.track[i].image[0]['#text']
It's just a key name inside of the object. You cannot access it via dot notation since it contains an invalid characters but you can use bracket notation. Here's a really simple example demonstrating this.
var foo = {
'#bar': 'http://www.google.com/'
}
foo['#bar'] // will return a string value of http://www.google.com/
If your key contains any invalid characters it must be encased in a string. In your case, you're getting a JSON response which always contain string-encased key names.
Hope this helps!

Categories

Resources