I would like to format my data with a key to access the information. This is what I currently have:
const dict = [];
dict.push({"student": "Brian", "id":"01", "grade":"Sophomore"})
return dict;
Output:
{
"student":"Brian"
"id": "01",
"grade": "Sophomore"
}
However, I am interested in creating this type of format with my data:
{
"student":"Brian" [
{
"id":"01",
"grade": "Sophomore"
}
]
}
How would I be able to do so? I would like to use "student" as my key to access the rest of its information associated.
You're basically there. However objects always need keys to go along with the values, so you need to assign a key to the object you want to create
const dict = [];
dict.push({
"Brian": {
"id": "01",
"grade": "Sophomore"
}
})
// to retrieve:
let brian = dict.filter(e=>Object.keys(e)[0]==="Brian").flatMap(Object.values)
if (brian && brian.length>0) console.log(brian[0])
//You could also set up your `dict` like this:
const dict2 = {};
dict2["Brian"] = {
"id": "01",
"grade": "Sophomore"
};
//and that would allow you to retrieve your object with
brian = dict2.Brian;
console.log(brian)
This question already has answers here:
How to get a subset of a javascript object's properties
(36 answers)
Closed 3 years ago.
I have one JSON Object and I want to create subset of JSON with particular keys values.
JSON Object
{
"Checksum": "OK",
"ID": "012B4567",
"DOB: "12-12-1991"
"Data": "Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>",
"issue: "11-April-2015",
"DocID": "PASSPORT",
"Number: "123456789",
"Document": "PASSPORT",
"Photo": "Qk06AAAAAAAAA",
"ExpiredFlag": false,
"ExpiryDate": "01 Apr 12",
"Forename": "IMA Phoney",
"Image2": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"ImageSource1": 0,
"Image3": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"Image1": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"IssueState: "USA",
"Nationality": "USA",
"PlaceOfBirth": "U.S.A",
"SecondName": "J",
"Sex": "Male",
"Surname": "XYZ"
}
I want subset from above like below:
{
"ID": "012B4567",
"Number: "123456789",
"Document": "PASSPORT",
"IssueState: "USA",
"Nationality": "USA",
"PlaceOfBirth": "U.S.A",
"SecondName": "J",
"Sex": "Male",
"Surname": "XYZ"
}
I have tried below code. It is working fine, But I am not able to understand. I need simplest way:
var data={
"CDRValidation": "CDR Validation test passed",
"AirBaudRate": "424",
"ChipID": "012B4567",
"BACStatus": "TS_SUCCESS",
"SACStatus": "TS_NOT_PERFORMED",
"Data": "Test Line 1 >>>>>\nTest Line 2 >>>>>\nTest Line 3 >>>>>",
"DocType": "PASSPORT",
"DocNumber": "123456789",
"DocID": "PASSPORT",
"Surname": "Person",
"Forename": "IMA Phoney",
"SecondName": "J",
"Nationality" : "Imaging Automation Demo State",
"Sex": "Male",
"DOB": "12 May 70",
"ExpiryDate": "01 Apr 12",
"IssueState": "Passport Agency Billerica",
"ExpiredFlag": false,
"ImageSource": 0,
"OptionalData1": "123456789123456",
"OptionalData2": "",
"DateOfIssue":"11 April 02",
"PlaceOfBirth":"Illinois, U.S.A"
}
console.log("----------------->",data);
var Fields = ({
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
} = data, {
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
})
console.log("--------subset--------->",Fields);
There are multiple ways you can handle this case. Object destructuring as you have done in your example is one simple way. You can also use an array to store the required keys and write code as below
function subset(parentObj) {
const keys = ['key1', 'key2', 'key3'];
const obj = {};
for (let i = 0, length = keys.length; i < length; i += 1) {
obj[keys[i]] = parentObj[keys[i]];
}
return obj;
}
Or you can also use the above code with some functional programming
function subset(parentObj) {
const keys = ['key1', 'key2', 'key3'];
return keys.reduce((acc, key) => ({
...acc,
[key]: parentObj[key];
}), {});
}
A simple to achieve what you are asking using ES5 is to create a list of all the properties you want to keep, and using Array#reduce add each property to a new object.
// Saves vertical space for example
var original = JSON.parse(`{"Checksum":"OK","ID":"012B4567","DOB":"12-12-1991","Data":"Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>","issue":"11-April-2015","DocID":"PASSPORT","Number":"123456789","Document":"PASSPORT","Photo":"Qk06AAAAAAAAA","ExpiredFlag":false,"ExpiryDate":"01 Apr 12","Forename":"IMA Phoney","Image2":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","ImageSource1":0,"Image3":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","Image1":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","IssueState":"USA","Nationality":"USA","PlaceOfBirth":"U.S.A","SecondName":"J","Sex":"Male","Surname":"XYZ"}`);
var propertiesToUse = ["ID", "Number", "Document", "IssueState", "Nationality", "PlaceOfBirth", "SecondName", "Sex", "Surname"];
var result = propertiesToUse.reduce(function(result, key) {
return result[key] = original[key], result;
}, {});
console.log(result);
What you have done is a simple way, but if you are confused with it, you can divide it into two lines and explain it.
This line actually destrucutes your object and assign the value for the mentioned keys in the object to the corresponding variables.
{
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
} = data
Now, each of this variable has data individually, but we want it in an object. Therefore, we use the second part, i.e. creating an object with the following variable acting as keys.
{
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
}
When combined you get the desired result in a single statement.
I have this normal array
["Company="Google",Country="USA",Id="123"", "Company="Volvo",Country="SWEDEN",Id="999""]
And I would like to build an object out of its values.
Expected result is
{
"root": [{
"Company": "Google",
"Country": "USA",
"Id": "123"
}, {
"Company": "Volvo",
"Country": "SWEDEN",
"Id": "999"
}
]
}
How do I work this structure in JavaScript?
the array you posted is not valid we'll need to mix single and double quotes like this:
['Company="Google",Country="USA",Id="123"', 'Company="Volvo",Country="SWEDEN",Id="999"']
if you're getting the array as a response from a request and you copied it from console than it quotes must've been escaped using \" and you don't have to fix it.
converting the array into an object:
var myArray = ['Company="Google",Country="USA",Id="123"', 'Company="Volvo",Country="SWEDEN",Id="999"']
var myObject = array2obj(myArray);
function array2obj(myArr) {
var myObj = {root:[]}
myArr.forEach(function(v) {
var currentObj = {}
v.split(",").forEach(function(vi) {
var tmp = vi.replace(/\"/g, "").split("=");
currentObj[tmp[0]] = tmp[1];
});
myObj.root.push(currentObj);
});
return myObj
}
as you can see you call the function like this var myObject = array2obj(myArray) assuming your array is stored in myArray.
now you have your object in the variable myObject:
{
"root": [
{
"Company": "Google",
"Country": "USA",
"Id": "123"
},
{
"Company": "Volvo",
"Country": "SWEDEN",
"Id": "999"
}
]
}
"reducing" the array into ids only:
as asked in comments, the following will produce a newArray = ["123", "999"]
var myArray = ['Company="Google",Country="USA",Id="123"', 'Company="Volvo",Country="SWEDEN",Id="999"'];
var newArray = myArray.map(function(x) {
var id = /,\s*id\s*=\s*"(.*?)"/gi.exec(x);
if (id) return id[1]
});
I'm using regex to match the id and .map() to create a new array with the matched results.
if you want the array to contain numbers and not strings replace return id[1] with return Number(id[1]) but you have to make sure ids are always numbers or you will get NaN errors
How can I replace the spaces in a JSON object's keys dynamically? For example, if I have the following object:
[{
"FIRST NAME": "Philip",
"LAST NAME": "Rivers",
"NUMBER": "17",
"GPA": "1.0",
"OLD_FACTOR": "8",
"NICENESS": "1"
}, {
"FIRST NAME": "Peyton",
"LAST NAME": "Manning",
"NUMBER": "18",
"GPA": "4.0",
"OLD_FACTOR": "5000",
"NICENESS": "5000"
}]
I want to be able to dynamically rename "FIRST NAME" and "LAST NAME" to "FIRST_NAME" and "LAST_NAME" respectively. Based on research so far, I have this function:
function replaceSpaces(data) {
debugger;
for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
var replacedKey = key.split(' ').join('_');
data[i][obj] = replacedKey;
}
}
return data;
}
The "data" parameter being passed in is an object that has already had JSON.parse ran on it prior to entering this function.
My issue with this code is that it's looping through the keys just fine, and assigning the proper replaced string to "replacedKey", but it's not assigning that to the original data object.
Here's complete code using forEach.
The steps are same as Quentin has stated in his answer
Copy the value
Remove the key-value from the object
Add new item with new value in the object
var arr = [{
"FIRST NAME": "Philip",
"LAST NAME": "Rivers",
"NUMBER": "17",
"GPA": "1.0",
"OLD_FACTOR": "8",
"NICENESS": "1"
}, {
"FIRST NAME": "Peyton",
"LAST NAME": "Manning",
"NUMBER": "18",
"GPA": "4.0",
"OLD_FACTOR": "5000",
"NICENESS": "5000"
}];
// Iterate over array
arr.forEach(function(e, i) {
// Iterate over the keys of object
Object.keys(e).forEach(function(key) {
// Copy the value
var val = e[key],
newKey = key.replace(/\s+/g, '_');
// Remove key-value from object
delete arr[i][key];
// Add value with new key
arr[i][newKey] = val;
});
});
console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="result"></pre>
Strictly if the JSON is get in the form of String from server:
Replace the spaces by _ from the keys.
JSON.parse(jsonString.replace(/"([\w\s]+)":/g, function (m) {
return m.replace(/\s+/g, '_');
}));
You need to:
Copy the value
Delete the old property
Modify the correct object. (data[i][obj] will convert obj to a string and try to use it as a property name).
Such:
for (var original_property in obj) {
var new_property = original_property.split(' ').join('_');
obj[new_property] = obj[original_property];
delete obj[original_property]
}
since it is JSON it is expected to come as string you could do it with a help of Regex.
var processedJson = yourJson.replace(/( +)(?=[(\w* *]*":)/g, "_");
var yourObj = JSON.parse(processedJson);
/( +)(?=[(\w* *]*":)/g will find all ocurances of within " ... ": which is a key on every JSON object.
I have a working version of a function to loop through a single array in a JSON object, e.g.
[{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}]
sample function:
function FindName(NameToFind, data1) {
objData = JSON.parse(data1);
for (var i = 0; i < objData.length; i++) {
var Name = objData[i].Name;
if (Name == NameToFind) {
alert("found!");
}
}
}
Now I need to change this function to allow for either single OR multiple arrays e.g.
{
"Table1": [{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}],
"Table2": [{
"Name": "Sarah",
"Surname": "Parker"
},
{
"Name": "Jonah",
"Surname": "Hill"
}
]
}
Is there a way to determine whether the object has 1 array (like in first example) or more than one arrays (like in 2nd example), and any advice/guidance on how to extend the function to be able to loop through all the items whether it has 1 array or multiple arrays?
Your first object is an array, the second one isn't.
You can test if your argument is an array, or even just test
if (objData[0]) // that's an array
EDIT :
if you want to iterate over all properties of a (just json decoded) object, when it's not an array, you can do this :
for (var key in objData) {
var value = objData[key];
// now use the key and the value
// for example key = "Table1"
// and value = [{"Name":"John","Surname":"Johnson"}, ... ]
}