Retrieving values nested in object [duplicate] - javascript

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 8 years ago.
Problem: Create a javascript function that takes an object (of any size and depth), iterates through it and runs some basic string replacing on any strings and returns the object with the amended values.
I have two ideas about the implementaion, but cannot get a solution for either:
var context = {
"test1": "123",
"test2": "123",
"test2.2": "123",
"test3": {
"test4": "cats",
"test5": {
"test6": "test1",
"test123": "1231232"
}
}
};
Idea 1)
Loop the array, and change the values,
http://php.net/manual/en/language.references.pass.php
In some way similar to PHP
Idea 2)
Build an array of path(s) to the object, so to replace the "test123" value I can create such an array:
['test3', 'test5', 'test123']
... this part is simple, but how do I then convert this to something like:
context['test3']['test5']['test123'] ?
Thankyou in advance.

Loop over the object and invoke the function recursively if the value at hand is an object. In pseudocode:
function replaceInObject ( obj, find, repl)
for key in obj
value = obj[key]
if value is object
obj[key] = replaceInObject(value, find, repl)
else
obj[key] = value.replace(find, repl)
return obj

Related

Cannot access a JSON attribute in a converted array [duplicate]

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Closed 2 months ago.
I would like to understand what am I doing wrong here. The problem is simple: I get an array in a response and I would need to access to its elements by name. Therefore I use Map to create a pair of Metric and Value. Subsequently, I use JSON stringify which I thought would be enough.
But when I try to access the element (array.Speed), I am getting Undefined.
var response=[
{
metric: "Speed",
value: "145",
},
{
metric: "Deceleration",
value: "76.5",
}
];
let array=[];
response.map(m=> {
array.push({
[m.metric]:m.value
});
});
var j=JSON.stringify(array);
console.log(j.Speed); //UNDEFINED
var js=JSON.parse(j);
console.log(js.Speed); //UNDEFINED
Stringify and access, converting to JSON later even, as described.
array is : [ { Speed: '145' }, { Deceleration: '76.5' } ] You can access speed like this: js[0].Speed .
The fact that j.Speed is undefined is to be expected since j is a string (and not an array neither an object)

Why for in loop returns string instead of my object? [duplicate]

This question already has answers here:
How to get all properties values of a JavaScript Object (without knowing the keys)?
(25 answers)
Closed 4 years ago.
i have nested object:
var obj = {
nestobj1:{
title: "some 1 title",
text: "some text"
},
nestobj2:{
title: "some 2 title",
text: "some text"
}
}
I am using for in loop
for ( let s in obj) {
console.log(s);
}
Console logs strings: nestobj1 and nestobj2. Why?
Why it dont returns/logs object ? Why it is string ? Please forgive me i quite new in Javascript.
The for...in statement iterates over all enumerable properties of an object.
The way you do it you only get the property name of the object without its value.
If you want to get the nested objects (the values) then you need to do it like that:
for ( let s in obj) {
console.log(obj[s]);
}

Parsing JSON keys into array of strings [duplicate]

This question already has answers here:
Get array of object's keys
(8 answers)
Closed 4 years ago.
I am currently trying to handle a GET request that returns a body in application/json structured like this:
{
"items": {
"item001": {"id":1234, "name": "name001"},
"item002": {"id":1235, "name": "name002"},
"item003": {"id":1236, "name": "name003"}
}
}
I'm trying to get an array of strings that looks like
array = ["item001", "item002", "item003"];
I don't care about any of the underlying hierarchy, I just need the key of each object as an array. I've tried several different methods (map(), JSON.stringify(), etc) but I can't seem to index each key in a array[i] format.
In fact, each time I try to even print the name of a single key, for example
var obj = JSON.parse({'whole json here'});
print(obj.items[1]);
I get an [object Object] error, which makes sense as obj.items is not indexed with a key other than "item001" for example. However, I do not know what the key for each object will be, hence the need for an array of the keys. Thank you in advance!
You can do Object.keys.It will return an array of the keys of an object
var x = {
"items": {
"item001": {
"id": 1234,
"name": "name001"
},
"item002": {
"id": 1235,
"name": "name002"
},
"item003": {
"id": 1236,
"name": "name003"
}
}
}
var y = Object.keys(x.items);
console.log(y)
You can use Object.keys(). For Reference
var obj={"items":{"item001":{"id":1234,"name":"name001"},"item002":{"id":1235,"name":"name002"},"item003":{"id":1236,"name":"name003"}}};
var result = Object.keys(obj.items);
console.log(result);
Object.keys will do that.
var obj = JSON.parse({'your json'});
console.log( Object.keys(obj.items) );

accessing specific part of JSON object with text string of keys [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 5 years ago.
I have performed diff of two json files with the output being an array of strings indicating the location within a json tree.
The original json file is something along the lines of:
{
'key': {
'key3': 'value'
},
'key1': {
'key2': 'value2'
}
'key5': {
'key4': 'value4'
}
}
And the output of the diff is:
[
'key.key3',
'key1.key2'
]
I'm able to cycle through all the strings in the array:
(difference).forEach((k) => {
console.log(k);
})
How do I access the value from the original json file using the strings set by the forEach() function above? I want something like what would be returned if I called originalJSON.key1.key2 directly, but it has to be made up by the strings in the above function.
I've tried originalJSON[k] but that just returns undefined.
You have to split 'key.key3' into 'key' and 'key3'.
One way to do this is just to 'key.key3'.split(".") which gives ['key','key3']
Then you can use them to navigate through your original object :
(difference).forEach( k => {
var keys = k.split(".") // ['key','key3']
var val = originalJSON[keys[0]][keys[1]] // == originalJSON['key']['key3']
console.log(val); // 'value', 'value2', 'value4'
})

Angular2 Typescript how to retrieve an array from inside an object [duplicate]

This question already has answers here:
Find a value in an array of objects in Javascript [duplicate]
(20 answers)
Closed 5 years ago.
When I do console.log of the following:
console.log(this.categories);
I get this structure:
which was created from this json from the api:
[
{
"id":"dff0bb3e-889f-43e6-b955-52cc7203952f",
"name":"Wood",
"category_types":[
{
"id":"49b31f43-d98d-43c8-9798-088ec6914fe5",
"name":"Solid"
},
{
"id":"8592716a-ffd5-4e97-ba9e-6a64ba6e48f1",
"name":"Engineered"
}
]
},
{
"id":"6b2b6914-6c64-4389-a327-be3f08fd066d",
"name":"Carpet",
"category_types":[
{
"id":"0e2c8473-90fb-4806-a6e7-2389eeb0f9e4",
"name":"Loop pile"
},
{
"id":"3c762653-4f0d-42d2-a84e-133c7051c95b",
"name":"Cut pile"
},
{
"id":"0997d4dc-e886-46ef-83b4-d90c4fb72553",
"name":"Cut \u0026 loop pile"
}
]
}
]
Given that I have the value 'Wood' in a string variable called value, how do I get hold of the category_types array for the Wood object?
console.log(this.categories[value]);
returns undefined.
You want to find object that has name of 'Wood', then get category_types. Array.prototype.find returns first value that meets the condition in the provided test function. In your case, it could look like this:
this.categories.find(value => value.name === 'Wood').category_types
You can use Array.filter:
let wood = this.categories.filter(category => {
return category.name === "Wood";
})[0];
This will filter your categories to retrieve the ones with name wood, then you take the first one. If you didn't find anything with name === "Wood" in your array, then it will be undefined.

Categories