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

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'
})

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)

Getting access to the inner object of a json [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 1 year ago.
I'm using Ant Design framework for my react project. I want to get access to the inner object "quote.USD.price" and put it on the dataSource array but unfortunately, I don't know how.
From what I understand you are looking for something like this. You can access inner fields of objects in any of the below methods
const crypto = {
quote: {
USD: {
price: 10
}
}
}
const data1 = {
title: "price",
dataIndex: crypto.quote.USD.price,
key: "id"
}
const data2 = {
title: "price",
dataIndex: crypto["quote"]["USD"]["price"],
key: "id"
}
console.log(data1)
console.log(data2)
//both should output the same
I think you want to parse a string that is concatenated with dots that represents the location of a value inside some nested objects.
I wrote a utility function to recursively does that. You can see it in action in this React project. I did it with TypeScript but you can remove the type annotations.
const findPriceByMultipleKeys = (dataKey: string, data: any): string | number => {
let keys: string[] = dataKey.split(".");
// If dataKey is one key without any dot notation, return the value
if(keys.length === 1) return data[dataKey];
let key: string = "";
let keysRest: string[] = [];
if (keys.length) {
// get first element from keys
// capture the rest of the keys
[key, ...keysRest] = keys;
}
// Check if there any more indexes left to evaluate
if (keysRest.length) {
// Transform keysRest to string concatenated with dots
let keysRestStr = keysRest.join(".");
// Let the function call itself to go deeper in the object with
// the remaining indexes and objects
return findPriceByMultipleKeys(keysRestStr, data[key]);
} else {
// If no keys left to evaluate, return the value
return data[key];
}
};

Assign javascript array to list of JSON objects with a property name? [duplicate]

This question already has answers here:
Javascript string array to object [duplicate]
(4 answers)
Closed 3 years ago.
I would like to convert a javascript array which looks like:
['https://www.google.com', 'https://www.facebook.com']
to a list of JSON objects that looks like this:
[{"redirectUri": "https://www.google.com"},
{"redirectUri": "https://www.facebook.com"}]
I have tried using Object.assign({}, array);
however this retuns json with the parameter name as the index of the array value and are all in a single object:
{"0": "https://www.google.com", "1": "https://www.facebook.com"},
is there a way to change this to use a custom parameter name dynamically?
You just need to map your elements respectively, using Array.map() method:
let result = arr.map(o => {
return {
"redirectUri": o
}
});
Demo:
let arr = ['https://www.google.com', 'https://www.facebook.com'];
let result = arr.map(o => {
return {
"redirectUri": o
}
});
console.log(result);

Convert Object to JSON Object

I am using DataTables library and I have hard times in receiving data in a proper format so I am trying to adjust it before DataTable library tries to fetch data into table. I have an ajax call which returns an object of the following format:
data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]
And my desired output is: data:[ [{ "SomeKey":"SomeValue" } , { ...} ],[...] ]
I have tried JSON.stringify or eval method , but did not worked , also tried those 2 methods when return type was some sort of string but then it inserts \ before " so It does not convert to json. Any help or good tracks would be appreciated.
This has nothing to do with JSON. :-)
data is apparently an array of arrays of objects, where each object has properties valled Key and Value.
If you want to create a new array of arrays of objects, where the objects have a property named by the Key value whose value is the Value value, you can do that like this:
data = data.map(a => a.map(({Key,Value}) => ({[Key]: Value})));
That uses map on the arrays (both the outer and inner ones) and destructuring to pick out the Key and Value properties from each object in the subarrays, and uses computed property names to set the property name on the new object.
In ES5 and earlier, that would look like this:
data = data.map(function(a) {
return a.map(function(obj) {
var newObj = {};
newObj[obj.Key] = obj.Value;
return newObj;
});
});
You should look into Array.prototype.map (mdn)
let data = [[{Key: "SomeKey", Value: "SomeValue"}]];
let output = data.map(a => a.map(({Key, Value}) => ({[Key]: Value})));
console.log(output);
Note the [Key] syntax. To put it simply, whereas var x = 'key'; y = {x: 3} will assign the object {x: 3}, x = 'key'; y = {[x]: 3} will assign the object {key: 3}.
If you're receiving literally the string "data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]", then you may trim the first 5 characters ('data:') and then use JSON.parse.

Retrieving values nested in object [duplicate]

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

Categories