Adding two new elements to existing JSON array - javascript

I have the following JavaScript object which prints the following JSON using
var str = JSON.stringify(finalNodesData, null, 2);
console.log(str);
Printed JSON
[
{
"jobDate": "2023-01-03 13:48:29.402",
"id": "b186c313-a2f3-44a8-9803-066c6d52e8a0"
},
{
"jobDate": "2023-01-03 13:57:19.988",
"id": "db182f5e-9622-42e9-bbe8-19bee4d878d4"
}
]
How can I add two new elements "submitedBy" and "submitReason" to the JSON? I want my JSON to look like
{
"submitedBy": "Bob Smith",
"submitReason": "Because of an error",
"nodeData": [
{
"jobDate": "2023-01-03 13:48:29.402",
"id": "b186c313-a2f3-44a8-9803-066c6d52e8a0"
},
{
"jobDate": "2023-01-03 13:57:19.988",
"id": "db182f5e-9622-42e9-bbe8-19bee4d878d4"
}
]
}
I want to use JavaScript variables to generate the JSON, and not concatenate strings.

Note: Your new JSON is no longer an Array, but an Object.
finalNodesData = {};
finalNodesData["nodeData"] = nodeData; // this is your old data
finalNodesData["submitedBy"] = "Bob Smith";
finalNodesData["submitReason"] = "Because of an error";
var str = JSON.stringify(finalNodesData, null, 2);
console.log(str);

The best way of doing this is adding the data to the JavaScript object before converting it to JSON.
let finalNodesData = [
{
jobDate: "2023-01-03 13:48:29.402",
id: "b186c313-a2f3-44a8-9803-066c6d52e8a0"
},
{
jobDate: "2023-01-03 13:57:19.988",
id: "db182f5e-9622-42e9-bbe8-19bee4d878d4"
}
]
const submittedBy = "Bob Smith"
const submitReason = "Because of an error"
finalNodesData = {
submittedBy,
submitReason,
nodeData: finalNodesData
}
var str = JSON.stringify(finalNodesData, null, 2);
console.log(str);

Related

How To Add A String Inside An Object For The Given Example

Hi iam finding the best way to add a string inside the given object.Any help would be appreciated
my String is 'created'
Down Below Is My Data
{
"id": "222",
"list": [
{
"name": "Tony",
}
],
iam trying to insert 'created' in the data like this
{
"id": "222",
"list": [
{
"name": "Tony",
"type":"created"
}
]
The string you've provided looks a lot like JSON data. You can convert a JSON string to an actual javascript object by using the JSON.parse(string) method.
With this object we then can query it's list property - which in your case is an array of objects - and add a new property type to each of the arrays elements. The final step is converting the object back to a JSON string using the JSON.stringify(object) method.
Here's an example:
let str = `{
"id": "222",
"list": [
{
"name": "Tony"
}
]
}`;
let data = JSON.parse(str);
data.list.forEach(element => {
element.type = "created";
});
str = JSON.stringify(data);
console.log(str);
const myObj = {
"id": "222",
"list": [
{
"name": "Tony",
}
],
};
myObj.list[0].type = "created";
This is the way you can do this. But you'd better use secified index of list items;
const index = 0; // Or any other way to get this
myObj.list[index].type = "created";

React native set array of dictionary in Array?

I need to show data in SectionList Component. for that i need to require data set to in array with dictionary.
Please check below code. where dictionary contains two value
Data : array and title : String
var dict = {};
dict['data'] = [
{"timing":[1,1,1,1],"title":"sunny"},
{"timing":[1,1,1,1],"title":"sunny"},
];
dict['title'] = "1";
const arrV = [dict]
console.log('item',arrV)
document.getElementById('result').innerText = JSON.stringify(arrV, null, 2)
<pre id="result"></div>
But When i print arrV.... there is no array in data key.(Array(0)) see the attached image. I need array with two objects. How can i achive that
Dictionary is normally called object in Javascript, If you want an array with two objects, here's how you can do that:
var dict1 = {};
var dict2 = {};
dict1["data"] = [
{"timing":[1,1,1,1],"title":"sunny"},
{"timing":[1,1,1,1],"title":"sunny"},
];
dict2["title"] = "1";
const arrV = [dict1,dict2]
console.log('item: ',arrV)
Here's how the result will look like
item: [
{
"data": [
{
"timing": [
1,
1,
1,
1
],
"title": "sunny"
},
{
"timing": [
1,
1,
1,
1
],
"title": "sunny"
}
]
},
{
"title": "1"
}
]

How to create a new json out of three jsons?

I have 3 different jsons, I need to extrapolate some data from each and create a new json with it. The three jsons have an id identifier in common, a unique identifier, so We could use that as a match since they are actually three different big jsons.
On json one we have "id":"265", on two and three "article_id":"265", so these can be the reference point when we loop.
I never worked with json this way so I wouldn't know how to approach it. I have put jQuery and JS as tags as they're what I know best.
1
{
"id":"265",
"title":"Battle of Gettysburg",
"page_id":"4849",
"language_id":"en",
"original_time":"July 1\u20133, 1863"
}
2
{
"id":"185",
"original_name":"United States",
"country_id":"24",
"article_id":"265"
}
3
{
"id":"73",
"month":"July",
"year":"1863",
"suffix":"",
"article_id":"265"
}
So the end result I am looking for is a single json exactly like this, we take id and title as objects from json 1, then we grab original_name from json two and year object from json three and we'll have:
{
"id":"265",
"title":"Battle of Gettysburg",
"original_name":"United States",
"year":"1863"
}
NOTE
The json above are just examples, in reality they are three huge lists, what I could do (manually), is to join them in order to have a single json.
There is some terminology confusion here; based on your comments you could be asking one of two very different questions. Fortunately one of them is very simple to answer so let's do both.
(I am handwaving past the details of loading json strings into the browser and converting them into javascript objects.)
If you have three objects
...then this is just a matter of plucking out the fields you need individually when constructing an output object:
var in1 = {
"id": "265",
"title": "Battle of Gettysburg",
"page_id": "4849",
"language_id": "en",
"original_time": "July 1\u20133, 1863"
};
var in2 = {
"id": "185",
"original_name": "United States",
"country_id": "24",
"article_id": "265"
}
var in3 = {
"id": "73",
"month": "July",
"year": "1863",
"suffix": "",
"article_id": "265"
}
// construct a new object using the selected fields
// from each object in1, in2, or in3:
var out = {
id: in1.id,
title: in1.title,
original_name: in2.original_name,
year: in3.year
}
console.log(out);
If you have three lists of objects:
...in this case it's a lot more complicated (and a lot more interesting). In this case you would need to match fields from the objects in each list which share the same IDs.
The following is definitely not the most efficient or memory-conserving way to do this; I've spread things out to (hopefully) make it easier to follow what it's doing.
I'm making two assumptions:
within each list, all IDs are unique (meaning you won't have two objects with the same ID in one JSON file)
Every ID will appear in all three lists (meaning you don't need to handle missing fields in output)
/* Again handwaving past loading JSON strings and parsing
them into javascript objects, we'll just start with
three arrays: */
var input1 = [{
"id": "265",
"title": "Battle of Gettysburg",
"page_id": "4849",
"language_id": "en",
"original_time": "July 1\u20133, 1863"
},
{
"id": "1",
"title": "Foo",
"page_id": "123",
"language_id": "en",
"original_time": "July 1\u20133, 1863"
}
];
var input2 = [{
"id": "1",
"original_name": "Bar",
"country_id": "24",
"article_id": "265"
},
{
"id": "265",
"original_name": "United States",
"country_id": "24",
"article_id": "265"
}
]
var input3 = [{
"id": "1",
"month": "July",
"year": "Baz",
"suffix": "",
"article_id": "265"
},
{
"id": "265",
"month": "July",
"year": "1863",
"suffix": "",
"article_id": "265"
}
]
/* It would be much easier to find corresponding IDs
across these arrays if they weren't arrays. We'll
start by converting them into objects keyed by the
item ids: */
var convertArray = function(arr) {
var output = {};
arr.forEach(function(o) {
output[o.id] = o;
});
return output;
}
var obj1 = convertArray(input1);
var obj2 = convertArray(input2);
var obj3 = convertArray(input3);
/* Now if we need to find (say) the object with id "foo", we don't
need to search the whole array, but can just use `obj1["foo"]` or
`obj1.foo`.
The last step is to iterate over the list of IDs and repeatedly
do basically the same thing as in the "if you have three objects"
part above. The only difference is that we need to access the
object with the same ID in each of the input lists: */
var constructOutput = function(in1, in2, in3) {
var output = []; // we'll be outputting a list of objects again.
// step through every ID (assuming in1 contains all of them):
Object.keys(in1).forEach(function(id) {
var obj = {
id: id,
title: in1[id].title,
original_name: in2[id].original_name,
year: in3[id].year
}
output.push(obj);
});
return output;
}
var final = constructOutput(obj1, obj2, obj3)
console.log(final)
Essentially what you have to do is mimic a SQL JOIN using JavaScript objects:
Use JSON.parse() on all three JSON collections to turn them into arrays of objects.
Iterate through JSON 1 objects; for each object...
Iterate through JSON 2 objects, testing if article ID matches the ID from JSON 1 that we are iterating over. Save this object.
Iterate through JSON 3 objects, testing if ID matches the ID of the object we found from JSON 2. Save this object.
After you have all three objects, make a new object literal that contains only the fields you want:
{
Id: obj1.id,
Title: obj1.title,
Original_name: obj2.original_name,
Year: obj3.year
}
Should you want to combine n number of JSON objects, e.g. a list of objects you can take a functional approach and utilise reduce + filter.
const data = [{
"id":"265",
"title":"Battle of Gettysburg",
"page_id":"4849",
"language_id":"en",
"original_time":"July 1\u20133, 1863"
},
{
"id":"185",
"original_name":"United States",
"country_id":"24",
"article_id":"265"
},
{
"id":"73",
"month":"July",
"year":"1863",
"suffix":"",
"article_id":"265"
}];
const final = data.reduce((accu, { id, title }, index, array) => {
// Find any related objects
const matches = array.filter(data => data.article_id === id);
if (matches.length) {
// Flatten them for ease of access. Duplicate keys will override.
const flat = matches.reduce((arr, item) => ({ ...arr, ...item }), [])
// Return new object
return accu.concat({
...flat,
id,
title,
});
}
return accu;
}, []);
console.log(final, '<<')
// Witness
document.getElementById('results').innerHTML = JSON.stringify(final);
<div id="results" style="font-family: Courier; font-size 14px; color: #fff; background: #000; padding: 20px; max-width: 80vw;"></div>
Edited*
Maybe this is what you need?
let arrPages = [{
"id":"265",
"title":"Battle of Gettysburg",
"page_id":"4849",
"language_id":"en",
"original_time":"July 1\u20133, 1863"
}];
let arrArticles = [{
"id":"185",
"original_name":"United States",
"country_id":"24",
"article_id":"265"
},
{
"id":"73",
"month":"July",
"year":"1863",
"suffix":"",
"article_id":"265"
}];
let getResult = (arrInput, arrCompare) => {
let joinedItems = [];
arrInput.forEach(item => {
let newItem = { id: item.id, title: item.title };
arrCompare.forEach(subItem => {
if(subItem.article_id !== undefined && subItem.article_id === item.id){
if(subItem.original_name !== undefined)
newItem.original_name = subItem.original_name;
if(subItem.year !== undefined)
newItem.year = subItem.year;
}
});
joinedItems.push(newItem);
});
return joinedItems;
};
let result = getResult(arrPages, arrArticles);
console.log(result);
In the first part of the code i create a var that has the json data.
To solve the problema i create 2 functions, the order of the creation dosen't metter, the first function getJSONData() take the json data as parameter and return a object filtered by the keys defined in the array keys. The secound function just check if the current key is present in the array of keys, this function could be replaced by the jQuery.inArray() method.
// JSON data
var json = [{
"id":"265",
"title":"Battle of Gettysburg",
"page_id":"4849",
"language_id":"en",
"original_time":"July 1\u20133, 1863"
},
{
"id":"185",
"original_name":"United States",
"country_id":"24",
"article_id":"265"
},
{
"id":"73",
"month":"July",
"year":"1863",
"suffix":"",
"article_id":"265"
}]
// keys that i want
var keys = ["title", "original_name", "year"];
// var that will have the filtered data
var newJSON = getJSONData(json);
console.log(JSON.stringify(newJSON))
// this is the main function of the code
// here we iterate in the json creating a new object that has all the tags definid in the keys array
function getJSONData(arrayJSON){
var JSONFiltered = {};
for(var i in arrayJSON){
for(var key in arrayJSON[i]){
if(hasElement(key)){
JSONFiltered[key] = arrayJSON[i][key];
}
}
}
return JSONFiltered;
}
// this function is used to check a key is present in the array of keys
function hasElement(key){
for(var elem in keys){
if(keys[elem] == key) return true;
}
return false;
}

convert return object to json but only certain value pairs

Yes I know there are heaps of posts about converting objects to json but my question is more specific..
Say Im calling some data from an api and the response is an object that looks like this
{
date: ...,
value: ...,
useless-info: ...,
useless-info: ...
}
now I know I can do this JSON.stringify(returnedobject);
so I get the newly formed json..
{
"date": ...,
"value": ...,
"useless-info": ...,
"useless-info": ...
}
now all I want in my newly formed json to be the "date" and "value" and remove the useless-info is this even possible?
any help would be appreciated!
Working Demo
var jsonObj = {
"date": "",
"value": "",
"useless-info": "",
"useless-info": ""
};
delete jsonObj["useless-info"];
var jsonString = JSON.stringify(jsonObj);
console.log(jsonString);
JSON.stringify() has a replacer param that can be used to limit output to a whitelisted array of keys you want to keep.
// Input.
const input = {
date: new Date(),
value: 8905934,
useless: 'useless',
extra: 'extra'
}
// Output.
const output = JSON.stringify(input, ['date', 'value'])
// Proof.
console.log(output)
const oldJson = {
"date": ...,
"value": ...,
"useless-info": ...,
"useless-info": ...
}
const newJson = {
"date" : oldJson.date,
"value": oldJson.value
}
You can either create a new object with the data you want, or delete the fields you don't need:
const someReturn = {
date: ...,
value: ...,
badstuff: ...
}
const goodObj = {
date: someReturn.date,
value: someReturn.value
}
Or to delete fields you can just call delete someReturn.badstuff

Creating custom JSON object

I am having the below JSON object.
"Department": [
{
"depType": "Testing",
"name": "xyz",
"address":""
},
{
"deptype": "Developer",
"name": "abc"
}
]
I want to create another object based on the type of deptartment (depType). Something like this
"Testing":{
"name": "xyz",
"address":""
},
"Developer":{
"name": "abc"
}
With the help of Object.keys, I was able to get the keys
You had some Property-naming issues with camelCased "depType". Fix that.
Create a new copy of the desired object to manipulate using JSON.parse(JSON.stringify(orgObj))
Loop that object to find the desired Property "Department"
Since Department is an Array of Objects you need to loop that Array for(var i=0; i<dep.length; i++).
Than you'll need to match if that Array contains arrObj.hasOwnProperty( "depType" )
if successful you can than fill your new object with all the info newObj[arrObj.depType] = arrObj;
Since now, inside your new object there's also the good old "depType" property you can get rid of it using delete.
jsBin demo
var myjson = {
"Department": [
{
"depType": "Testing", // NOTE: "camelCase"
"name": "xyz",
"address":""
},
{
"depType": "Developer", // FIX: "camelCase" !!
"name": "abc"
}
]
};
function depTypify( orgObj ) {
var objCopy = JSON.parse(JSON.stringify(orgObj)); // Fresh copy
var newObj = {};
for(var prop in objCopy){
if(prop === "Department") {
var dep = objCopy[prop]; // get Department Array
for(var i=0; i<dep.length; i++) { // Loop array
var arrObj = dep[i]; // Explore Each Array Object
if(arrObj.hasOwnProperty( "depType" )) {
newObj[arrObj.depType] = arrObj;
delete arrObj.depType; // We don't need it any more
}
}
}
}
return newObj;
}
var myNewJson = depTypify( myjson );
if you do than console.log( myNewJson ) this is what you'll get:
[object Object] {
Developer: [object Object] {
name: "abc"
},
Testing: [object Object] {
address: "",
name: "xyz"
}
}
The nice thing is that your old json is still intact.

Categories