Rearrange json files - javascript

I want to rearrange the following JSON which i am having trouble with. I want to convert a format of JSON object into the other for myself. Any help is appreciated. I Thank you.
From :
[
{"a":1,"b":2,"c":3,"d":4,"name":"chris"},
{"a":11,"b":21,"c":31,"d":41,"name":"chris1"},
{"a":12,"b":22,"c":32,"d":42,"name":"chris2"}
]
To:
[
{
"name": a,
"chris":1,
"chris1":11,
chris2:12
},
{
"name": b,
"chris":2,
"chris1":21,
chris2:22
},
{
"name": c,
"chris":3,
"chris1":31,
chris2:32
},
{
"name": d,
"chris":4,
"chris1":41,
chris2:42
}
]

Here's a snippet you could use
let json = [
{"a":1,"b":"2","c":3,"d":4,"name":"chris"},
{"a":11,"b":"21","c":31,"d":41,"name":"chris1"},
{"a":12,"b":"22","c":32,"d":42,"name":"chris2"}
]
let map = {};
for (const obj of json) {
for( const [key, value] of Object.entries(obj)) {
if (key === "name") continue;
if (typeof map[key] !== "object") {
map[key] = {name: key};
}
const data = map[key];
data[obj.name]= value;
}
}
console.log(map)

Related

Loop through nested array to return values of object

I have a nested array and what I was trying to do was get all the values of the object embedded inside the array. I am currently getting each embedded object and calling Object.values to get the values but this method isn't efficient when the array size is big. Is there a way to loop through the array and return the values of each object? Any help is appreciated. Thanks in advance.
const data = [{"path":"uploads\\20211115000755-package.json"},{"path":"uploads\\20211115012255-index.html"},{"path":"uploads\\20211115014342-dataServerMid.js"},{"path":"uploads\\20211115031212-index.js"},{"path":"uploads\\20211115031218-uploadDataServer.js"},{"path":"uploads\\20211115031232-index.js"},{"path":"uploads\\20211115031244-dataServerMid.js"},{"path":"uploads\\20211115031250-uploadData.css"},{"path":"uploads\\20211115031303-20211115012255-index.html"},{"path":"uploads\\20211115031318-20211115031303-20211115012255-index.html"},{"path":"uploads\\20211115050204-exportsCapture.JPG"},{"path":"uploads\\20211115052347-[FREE] Stunna 4 Vegas x DaBaby x NLE Choppa Type Beat Call of Duty (320 kbps).mp3"},{"path":"uploads\\20211115200304-Readme.docx"},{"path":"uploads\\20211115202751-Visual Artist Series Fall 2019Corrected.docx"},{"path":"uploads\\20211115203354-ln command examples.docx"},{"path":"uploads\\20211115210027-Q2.docx"},{"path":"uploads\\20211116011817-Fall 2019 ABCD Plattsburgh Syllabi Course Description.docx"}]
//change this to loop and return all the values instead of having to call by index
const dataValues = [Object.values(data[0]).toString(), Object.values(data[1]).toString(), Object.values(data[2]).toString()]
console.log(dataValues)
UPDATE: I tried #yousaf's method. It worked for my 3 item array but not for this:
const data = [{
"path": "uploads\\20211115000755-package.json"
}, {
"path": "uploads\\20211115012255-index.html"
}, {
"path": "uploads\\20211115014342-dataServerMid.js"
}, {
"path": "uploads\\20211115031212-index.js"
}, {
"path": "uploads\\20211115031218-uploadDataServer.js"
}, {
"path": "uploads\\20211115031232-index.js"
}, {
"path": "uploads\\20211115031244-dataServerMid.js"
}, {
"path": "uploads\\20211115031250-uploadData.css"
}, {
"path": "uploads\\20211115031303-20211115012255-index.html"
}, {
"path": "uploads\\20211115031318-20211115031303-20211115012255-index.html"
}, {
"path": "uploads\\20211115050204-exportsCapture.JPG"
}, {
"path": "uploads\\20211115052347-[FREE] Stunna 4 Vegas x DaBaby x NLE Choppa Type Beat Call of Duty (320 kbps).mp3"
}, {
"path": "uploads\\20211115200304-Readme.docx"
}, {
"path": "uploads\\20211115202751-Visual Artist Series Fall 2019Corrected.docx"
}, {
"path": "uploads\\20211115203354-ln command examples.docx"
}, {
"path": "uploads\\20211115210027-Q2.docx"
}, {
"path": "uploads\\20211116011817-Fall 2019.docx"
}]
//change this to loop and return all the values instead of having to call by index
const dataValues = data.map((obj, idx) => obj["path" + (idx + 1)])
console.log(dataValues)
Use a for...of to iterate over the array, and then push the value to a new array.
const data=[{path1:"uploads\\20211115000755-package.json"},{path2:"uploads\\20211115012255-index.html"},{path3:"uploads\\20211115014342-dataServerMid.js"}];
const arr = [];
for (const obj of data) {
const [value] = Object.values(obj);
arr.push(value);
}
console.log(arr);
Or you can use map.
const data=[{path1:"uploads\\20211115000755-package.json"},{path2:"uploads\\20211115012255-index.html"},{path3:"uploads\\20211115014342-dataServerMid.js"}];
const arr = data.map(obj => {
const [value] = Object.values(obj);
return value;
});
console.log(arr);
Use for loop for iterate data
const data = [{
"path1": "uploads\\20211115000755-package.json"
}, {
"path2": "uploads\\20211115012255-index.html"
}, {
"path3": "uploads\\20211115014342-dataServerMid.js"
}]
const dataValues = [];
for(var i = 0; i < data.length; i++)
{
dataValues.push(Object.values(data[i]).toString())
}
console.log(dataValues)
This may help You. Try it out..
function nestedLoop(obj) {
const res = {};
function recurse(obj, current) {
for (const key in obj) {
let value = obj[key];
if(value != undefined) {
if (value && typeof value === 'object') {
recurse(value, key);
} else {
// Do your stuff here to var value
res[key] = value;
}
}
}
}
recurse(obj);
return res;
}

Renaming object keys which are nested

I am accessing JSON which looks like this.
[
{
"itemType": "SelectionTitle",
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"item.Type": "SelectionFile",
"name": "1105F.MID",
"active": true,
"isFactory.Default": false,
"selection.Type": "Music",
"sfzFile": "",
"destination": "/data/uploads",
"encoding": "7bit",
"fieldname": "file",
"filename": "782f49a7cd72b865b4e2d286816792e7"
...
}
}, ...
And I am having trouble renaming the object keys which have the . in the name to an _. For example:
item.Type or selection.Type to item_Type or selection_Type.
This is what I am trying to use:
var json = jsonFromExampleAbove;
str = JSON.stringify(json);
str = str.selectionFile.replace(/\".\":/g, "\"_\":");
json = JSON.parse(str);
console.log(json);
I am getting a console log error. I think it is because the values I am trying to replace are nested, but not sure. I am still very much a beginner here.
Thank you.
I would be tempted to do it with a bit of recursion using Object.entries and Object.fromEntries
const input = [
{
"itemType": "SelectionTitle",
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"item.Type": "SelectionFile",
"name": "1105F.MID",
"active": true,
"isFactory.Default": false,
"selection.Type": "Music",
"sfzFile": "",
"destination": "/data/uploads",
"encoding": "7bit",
"fieldname": "file",
"filename": "782f49a7cd72b865b4e2d286816792e7"
}
}];
function replaceDots(obj){
return Object.fromEntries(Object.entries(obj).map( ([key,value]) => {
const newKey = key.replace(".","_");
return typeof value == "object"
? [newKey, replaceDots(value)]
: [newKey, value]
}));
}
const result = input.map(replaceDots);
console.log(result);
Your solution with a replaceAll on the stringified JSON could result in unwanted problems when a value contains a dot.
For renaming nested keys of an object you need go over the object recursively and assign the new keys while removing the old ones
// for ES6
function renameKey(obj) {
// loop over all keys
for (let k in obj) {
// apply recursively if value is an object
if (typeof obj[k] === "object" && obj[k] !== null)
renameKey(obj[k]);
// only replace keys of type String
if (typeof k === 'string' || k instanceof String) {
const newKey = k.replaceAll(".", "_");
// assign {newKey:value} to object and delete old key
delete Object.assign(obj, { [newKey]: obj[k] })[k];
}
}
return obj
}
You can use a recursive approach to replace the keys in the input object(s) with your desired result. There's no need to use JSON.stringify(), one can simply iterate through the objects.
We'll use searchValue to specify what we wish to search for and newvalue to specify the replacement, in this case they will be /./g and '_'.
let arr = [
{
"itemType": "SelectionTitle",
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"item.Type": "SelectionFile",
"name": "1105F.MID",
"active": true,
"isFactory.Default": false,
"selection.Type": "Music",
"sfzFile": "",
"destination": "/data/uploads",
"encoding": "7bit",
"fieldname": "file",
"filename": "782f49a7cd72b865b4e2d286816792e7"
}
}
]
function replaceKeys(obj, searchvalue, newvalue, newObj) {
if (!newObj) newObj = Array.isArray(obj) ? []: {};
for(let k in obj) {
let newKey = k.replace(searchvalue, newvalue);
if (typeof(obj[k]) === 'object') {
newObj[newKey] = Array.isArray(obj[k]) ? []: {};
replaceKeys(obj[k], searchvalue, newvalue, newObj[newKey])
} else {
newObj[newKey] = obj[k];
}
}
return newObj;
}
const result = replaceKeys(arr, /\./g, '_');
console.log('Result:', result);

convert nested array to JSON string in js?

I have a set of array like this : [["Sarah"],["Jamie"],["B"],["148"]]
and I want to convert this into JSON string with specific element for each vaues. For example,
{ "name":"Sarah", "grade":"148", "School":"B"...}
How should I proceed? I tried to toString the array then bind with this element but it doesn't work out well..
Original Json
"Data":{
"Table":[
{
"Name":[
"Jamie"
],
"School":[
"A"
],
"grade":[
"99"
]
},
{
"Name":[
"Mike"
],
"School":[
"B"
],
"grade":[
"148"
]
}
]
}
}
You can try with the simple forEach
var data = {"Data": {"Table": [{"Name": ["Jamie"],"School": ["A"],"grade": ["99"]},{"Name": ["Mike"],"School": ["B"],"grade": ["148"]}]}};
var items = [];
data['Data']['Table'].forEach(function(item){
items.push({name: item.Name[0], grade: item.grade[0], school: item.School[0]});
});
console.log(JSON.stringify(items));
You can use reduce to do this!
let newData = data.Data.Table.reduce(function(arr, obj) {
let newObj = {};
for (let key in obj) {
newObj[key] = obj[key][0]
}
arr.push(newObj);
return arr;
}, [])
Demo: https://jsfiddle.net/500eo2gp/
let newDataArray = this.data.Data.Table.reduce(function(arr, obj) {
let newObj = {};
for (let key in obj) {
newObj[key] = obj[key][0]
}
arr.push(newObj);
return arr;
}, []
);
newData =JSON.stringify(newDataArray);
JSON.stringify(newDataArray) array from tymeJV 's code snippet will give you the JSON string as follows.
[{"Name":"Jamie","School":"A","grade":"99"},{"Name":"Mike","School":"B","grade":"148"}]
Demo:
http://plnkr.co/edit/wPhVTOFhRgERLXKCuoYl?p=preview

How to get all key in JSON object (javascript)

{"document":
{"people":[
{"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
{"name":["hermione granger"],"age":["18"],"gender":["Female"]},
]}
}
From this JSON example, I would like to get the keys such as name, age, gender for each people.
How to do this?
I use Object.keys which is built into JavaScript Object, it will return an array of keys from given object MDN Reference
var obj = {name: "Jeeva", age: "22", gender: "Male"}
console.log(Object.keys(obj))
Try this
var s = {name: "raul", age: "22", gender: "Male"}
var keys = [];
for(var k in s) keys.push(k);
Here keys array will return your keys ["name", "age", "gender"]
var input = {"document":
{"people":[
{"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
{"name":["hermione granger"],"age":["18"],"gender":["Female"]},
]}
}
var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
Object.keys(input.document.people[i]).forEach(function(key){
if(keys.indexOf(key) == -1)
{
keys.push(key);
}
});
}
console.log(keys);
ES6 of the day here;
const json_getAllKeys = data => (
data.reduce((keys, obj) => (
keys.concat(Object.keys(obj).filter(key => (
keys.indexOf(key) === -1))
)
), [])
)
And yes it can be written in very long one line;
const json_getAllKeys = data => data.reduce((keys, obj) => keys.concat(Object.keys(obj).filter(key => keys.indexOf(key) === -1)), [])
EDIT: Returns all first order keys if the input is of type array of objects
var jsonData = { Name: "Ricardo Vasquez", age: "46", Email: "Rickysoft#gmail.com" };
for (x in jsonData) {
console.log(x +" => "+ jsonData[x]);
alert(x +" => "+ jsonData[x]);
}
This function should return an array of ALL the keys (i.e. the key names) in a JSON object including nested key/value pairs.
function get_all_json_keys(json_object, ret_array = []) {
for (json_key in json_object) {
if (typeof(json_object[json_key]) === 'object' && !Array.isArray(json_object[json_key])) {
ret_array.push(json_key);
get_all_json_keys(json_object[json_key], ret_array);
} else if (Array.isArray(json_object[json_key])) {
ret_array.push(json_key);
first_element = json_object[json_key][0];
if (typeof(first_element) === 'object') {
get_all_json_keys(first_element, ret_array);
}
} else {
ret_array.push(json_key);
}
}
return ret_array
}
Using this function on the OP's original object
const op_object =
{
"document":{
"people":[
{
"name":[
"Harry Potter"
],
"age":[
"18"
],
"gender":[
"Male"
]
},
{
"name":[
"hermione granger"
],
"age":[
"18"
],
"gender":[
"Female"
]
}
]
}
}
var all_keys = [];
function get_all_json_keys(json_object, ret_array = []) {
for (json_key in json_object) {
if (typeof(json_object[json_key]) === 'object' && !Array.isArray(json_object[json_key])) {
ret_array.push(json_key);
get_all_json_keys(json_object[json_key], ret_array);
} else if (Array.isArray(json_object[json_key])) {
ret_array.push(json_key);
first_element = json_object[json_key][0];
if (typeof(first_element) === 'object') {
get_all_json_keys(first_element, ret_array);
}
} else {
ret_array.push(json_key);
}
}
return ret_array
}
get_all_json_keys(op_object, all_keys);
console.log(all_keys);
should yield
[ 'document', 'people', 'name', 'age', 'gender' ]
Note: This will return a unique list of all key names.
We must "parse" our jsonObject
console.log('{"key0":"value0", "key1":"value1"}');
var jsonObject = JSON.parse('{"key0":"value0", "key1":"value1"}')
Object.keys(jsonObject).forEach(key => {
console.log(jsonObject[key]); //values
console.log(key); //keys
})

Getting the datatype of a json in JavaScript

Hi I have a below json value
{
"item": [
{
"id": "0001",
"data": {
"data1": [
{
"data2": [
{
"id": "5001",
"type": "None",
"dummyData": [
{
"data3": "5001",
"data4": [
{
"data5": "5001"
}
]
}
]
}
]
}
]
}
}
]
}
I need to find the jsonpath aand the datatype of the keys in the json object.(ie) jsonpath of item will be item=item and the datatype will be item = array of JSON objects.I'm able to find the jsonpath.Below is my code
var data={"item":[{"id":"0001","data":{"data1":[{"data2":[{"id":"5001","type":"None","dummyData":[{"data3":"5001","data4":[{"data5":"5001"}]}]}]}]}}]}
var keys = new Array();
keys = getKeys(keys, data, '');
console.log("key"+keys)
function getKeys(keys, obj, path) {
for (key in obj) {
var currpath = path + '.' + key;
keys.push([key, currpath]);
if (typeof(obj[key]) === 'object') {
if (obj[key] instanceof Array) { //added check for array
getKeys(keys, obj[key][0], currpath + '[]');
}
else
getKeys(keys, obj[key], currpath);
}
}
var jsonPath=[];
for (var i = 0; i < keys.length; i++) {
var json = new Array();
json = keys[i][1].replace(/^\.|\.$/g, '')
jsonPath[jsonPath.length]= keys[i][0] + '=' + json
}
return jsonPath;
}
here the console key prints the jsonpath of all the keys.I need to find the datatype.I'm stuck here any help will be much appreciated.

Categories

Resources