Value substitution while accessing nested json object - javascript

This is my json object
{
"a1": {
"b1": {
"name": "Tim",
"status": "Completed"
}
"c1" {
"field1": "name",
"field2": "status"
}
}
I need to access the value Tim by getting the field key within c1.
For example, I need to get the value of a1.c1.field1 which gives me the value name1 , then I need to access the value tim by a1.b1.(value of a1.c1.field1)
I do not know how to do this. Can someone give the possible ways to accomplish this?

var a1 =
{
"b1":
{
"name": "Tim",
"status": "Completed"
},
"c1":
{
"field1": "name",
"field2": "status"
}
};
console.log(a1.b1[a1.c1.field1]);
Do fix the error in your json too ;)

You can access using square brackets. With the data you provided,
var data = {
"a1": {
"b1": {
"name": "Tim",
"status": "Completed"
},
"c1":{
"field1": "name",
"field2": "status"
}
}
};
You can achieve your requirement by accessing.
data.a1.b1[data.a1.c1.field1]

Your JSON is a little off, so it's corrected below. This is an example of how to retrieve the value of field1 in the c1 object (in the a1 object)
$(document).ready(function () {
var json = {
"a1":
{
"b1":
{
"name": "Tim",
"status": "Completed"
},
"c1":
{
"field1": "name",
"field2": "status"
}
}
};
console.log(json.a1.b1.name); // returns Tim
// or
console.log(json["a1"]["b1"]["name"]); // returns Tim
});
Is this what you're looking for?

The obvious way is to use a1.c1.field1 as a property accessor using the bracket notation.
var obj = {
"a1": {
"b1": {
"name": "Tim",
"status": "Completed"
},
"c1": {
"field1": "name",
"field2": "status"
}
}
};
console.log(obj.a1.c1.field1); // 'name'
console.log(obj.a1.b1[obj.a1.c1.field1]); // 'Tim'
or, more legibly,
var key = obj.a1.c1.field1;
var value = obj.a1.b1[key];
console.log(value); // 'Tim'

Related

How do I convert JSON values into a key value pair pir

I have a JSON in the following format and need to convert the 2 values into a Key / Value pair in javascript
"column_values": [
{
"id": "status",
"text": "Working on it"
}
]
I need the result to be
"column_values"[{"status": "Working on it"}]
I need the code to iterate through the column_values array and convert all the sets of id and text pairs to the key = id value : Value = text:values
Is my result possible?
Additional Information...
I am parsing a response from monday.com api in zapier.
the api payload is contained in
const results = response.json;
the full api payload is
{
"data": {
"boards": [
{
"name": "Test Board",
"items": [
{
"name": "Name Change",
"id": "625495642",
"column_values": [
{
"id": "person",
"text": ""
},
{
"id": "subitems",
"text": "Subitem 1, Subitem 2"
},
{
"id": "status",
"text": "Working on it"
},
{
"id": "dropdown",
"text": "Test1"
},
{
"id": "formula",
"text": ""
}
]
}
]
}
]
},
"account_id": 1111
}
I need to the the code to parse the data and replace the column_values with the format above, and then pass the reformated payload to
return results;
You just Map the Array you start out with to an Array with the values.
var column_values = [ { "id": "status", "text": "Working on it" } ]
var KeyValuePairs = column_values.map(cv => [cv.id,cv.text]);
console.log(KeyValuePairs);
If every object is going to contain the id and text keys only, you can map it and delete the other keys.
column_values = column_values.map(item => {
item[item.id] = item.text;
delete item.id;
delete item.text;
return item;
});
try this
var column_values = [ { "id": "status", "text": "Working on it" } ]
var res = column_values.map(x => ({[x.id] : x.text}))
console.log(res)

Append string to JSON array element in JS

I have a specific format for a set of JSON objects. The format is as follows:
[{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6"]
}]
I am writing a function using simply JavaScript (no jQuery), that will append a value to the .value element based on if the user input matches a key value. For example, I input key2, the logic will match against key 2, and append "value7" to the end of the value element for that key, resulting in the following:
[{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6", "value7"]
}]
Currently the JSON is just an object in the JS file that is parsed using JSON.parse("string"). I would need to perform the appending and then rebuild the JSON using Stringify. (Assuming that would be my logic). I just need help with the appending because I am confused on the logic in this scenario. If anyone could throw together a quick example of how this would look in JS, that would be a massive help. Thank you!
You't target the object, and then the property containing the array, and push to that array
var array = [{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6"]
}];
array[1].value.push('value7');
console.log(array);
check this snippet
var arr = [{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6"]
}]
console.log(insertAtKey(arr, 2, "value7"));
function insertAtKey(arr, index, str) {
var obj = arr[index - 1];
Object.keys(obj).forEach(function(key, val) {
if (key === "value") {
obj[key].push(str);
}
});
arr[index - 1] = obj;
return arr;
}
Hope it helps
This question sounds like homework to me and I don't want to spoil the whole solution, but you can use a filter for searching in the object array, for adding the value you have the rest of the puzzle:
var data = [{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6"]
}];
function hasKey(k) {
return data.filter(e => { return e['key'].includes(k); });
}
console.log("for key1:" + hasKey("key1")[0].value);
console.log("for key2:" + hasKey("key2")[0].value);
console.log("for key3:" + hasKey("key3")[0].value);
What filter does:
e => { return e['key'].includes(k); } If the current object e in the data array includes a value k in the key attribute then pass the value.

Convert json object in to array to iterate through ng-repeat using Javascript? [duplicate]

This question already has answers here:
What is easy way to convert object in array Angular JS?
(3 answers)
Closed 6 years ago.
Here is my sample json , i am getting my json obj from firebase i have to convert the list in to array to bind in html trough ng-repeat.
my Json object is
{
"cats1": {
"Name": "cricket",
"imgUrl": "some url",
"list1": {
"bat": {
"Name": "bat",
"imgUrl": "some url",
"price": "$100"
},
"pads": {
"displayName": "pads",
"imgUrl": "some url",
"price": "$50"
}
}
},
"cats2": {
"Name": "football",
"imgUrl": "some url"
}
}
this is how i required
this is the array structure i required , when i add the new list it must store uniquely in cricket category.
[
{
"Name": "cricket",
"imgUrl": "some url",
"list1": [
{
"Name": "bat",
"imgUrl": "some url",
"price": "$100"
},
{
"displayName": "pads",
"imgUrl": "some url",
"price": "$50"
}
]
},
{
"Name": "football",
"imgUrl": "some url"
}
]
i am new to angular any one please help me to figure out this problem
Use Object.keys and pass them on to Array.prototype.map to create the array that you want - see demo below:
var object={cats1:{Name:"cricket",imgUrl:"some url",list1:{bat:{Name:"bat",imgUrl:"some url",price:"$100"},pads:{displayName:"pads",imgUrl:"some url",price:"$50"}}},cats2:{Name:"football",imgUrl:"some url"}};
var result = Object.keys(object).map(e=>object[e]);
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
EDIT:
Correcting the solution to make list1 an array:
var object={cats1:{Name:"cricket",imgUrl:"some url",list1:{bat:{Name:"bat",imgUrl:"some url",price:"$100"},pads:{displayName:"pads",imgUrl:"some url",price:"$50"}}},cats2:{Name:"football",imgUrl:"some url"}};
var result = Object.keys(object).map(function(e){
Object.keys(object[e]).forEach(function(k){
if(typeof object[e][k] == "object") {
object[e][k] = Object.keys(object[e][k]).map(function(l){
return object[e][k][l];
});
}
});
return object[e];
});
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
You can recursion but do note this can cause freeze for big objects and can also lead to Maximum Call Stack exceeded
Logic
Loop over object and check if all entries are objects.
If yes, then a simple Object.keys(obj).map(x=>obj[x]) will do.
If not, then you will have to copy individual values and if object, then again loop in it for inner objects. A simple way is to loop on every key and if type is not object, just return value.
function ObjectToArray(obj) {
if (typeof(obj) === 'object') {
var keys = Object.keys(obj);
var allObjects = keys.every(x => typeof(obj[x]) === 'object');
if (allObjects) {
return keys.map(x => ObjectToArray(obj[x]));
} else {
var o = {};
keys.forEach(x => {
o[x] = ObjectToArray(obj[x])
});
return o;
}
} else {
return obj;
}
}
var d={cats1:{Name:"cricket",imgUrl:"some url",list1:{bat:{Name:"bat",imgUrl:"some url",price:"$100"},pads:{displayName:"pads",imgUrl:"some url",price:"$50"}}},cats2:{Name:"football",imgUrl:"some url"}};
console.log(ObjectToArray(d))
You could do something like this, by iterating over the input object keys and stripping out the keys.
var app = angular.module("sampleApp", []);
app.controller("sampleController", ["$scope",
function($scope) {
$scope.result = {
"cats1": {
"Name": "cricket",
"imgUrl": "some url",
"list1": {
"bat": {
"Name": "bat",
"imgUrl": "some url",
"price": "$100"
},
"pads": {
"displayName": "pads",
"imgUrl": "some url",
"price": "$50"
}
}
},
"cats2": {
"Name": "football",
"imgUrl": "some url"
}
};
$scope.format = Object.keys($scope.result).map((key) => $scope.result[key])
}
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
<div ng-controller="sampleController">
<div>Formatted</div>
<pre>{{format | json}}</pre>
</div>
</div>

get value of a field from json

I have a JSON that looks like this:
{
"name": "A1",
"aaaaa": [
{
"name": "B1",
"teststr": [
{
"name": "C1",
"state": false,
},
{
"name": "C2",
"state": false,
}
]
},
{
"name": "B2",
"teststr": [
{
"name": "C3",
"state": false,
}
]
}
]
}
I am using JavaScript.
Now, within A1, I have to find a specific "testStr" with name "C1" and change its "state" from false to true. Keys "aaaaa" and "teststr" are unique. And all "teststr"s have unique name.
Can someone please help me with this?
You could go this way:
var smallObject = object.aaaaa.filter(function (o) {
return o.name === "B1";
})[0];
var smallerObject = smallObject.teststr.filter(function (o) {
return o.name === "C1";
})[0];
smallerObject.state = true;
Where object is the literal object that you mentioned in the problem definition.

how to parse json string contains circular reference in javascript?

I have the following json string in javascript. This string contains a circular references. I want to parse this string in such a way that the reference will be replaced by its actual object. I use Json.Parse but it creates the json object with references. Is there any way by whihc i can achieve this ?
{
"$id": "1",
"$values": [
{
"$id": "2",
"Event": {
"$id": "3",
"Invitaions": {
"$id": "4",
"$values": [
{
"$ref": "2"
},
{
"$id": "5",
"Event": {
"$ref": "3"
},
"Id": 2,
"Name": "test2",
"Date": "24",
"EventId": 1
}
]
},
"Id": 1,
"Name": "marriage",
"Address": "abcd"
},
"Id": 1,
"Name": "test1",
"Date": "23",
"EventId": 1
},
{
"$ref": "5"
},
{
"$id": "6",
"Event": {
"$id": "7",
"Invitaions": {
"$id": "8",
"$values": [
{
"$ref": "6"
}
]
},
"Id": 2,
"Name": "birthday",
"Address": "abcd"
},
"Id": 3,
"Name": "test3",
"Date": "25",
"EventId": 2
}
]
}
This should do it:
function resolveReferences(json) {
if (typeof json === 'string')
json = JSON.parse(json);
var byid = {}, // all objects by id
refs = []; // references to objects that could not be resolved
json = (function recurse(obj, prop, parent) {
if (typeof obj !== 'object' || !obj) // a primitive value
return obj;
if ("$ref" in obj) { // a reference
var ref = obj.$ref;
if (ref in byid)
return byid[ref];
// else we have to make it lazy:
refs.push([parent, prop, ref]);
return;
} else if ("$id" in obj) {
var id = obj.$id;
delete obj.$id;
if ("$values" in obj) // an array
obj = obj.$values.map(recurse);
else // a plain object
for (var prop in obj)
obj[prop] = recurse(obj[prop], prop, obj)
byid[id] = obj;
}
return obj;
})(json); // run it!
for (var i=0; i<refs.length; i++) { // resolve previously unknown references
var ref = refs[i];
ref[0][ref[1]] = byid[refs[2]];
// Notice that this throws if you put in a reference at top-level
}
return json;
}
You should check out Douglas Crockfords JSON-js repo on github: https://github.com/douglascrockford/JSON-js
There's a cycle.js in there that helps you do exactly what you're looking for.
Look at my post here, I've found some bugs in the code above and there wasn't arrays support, check out my improved version: Resolve circular references from JSON object

Categories