I am using map method to convert from an object to an array. What is the issue in the following code?
var data = {
"productName": "fsdfsdf",
"productDesc": "",
"category": null,
"categoryName": "",
"style": null,
"styleName": "",
"substyle": null,
"substyleName": "",
"store": null,
"storeName": "",
"stand": null,
"standName": "",
"rack": null,
"rackName": "",
"roll": null,
"rollName": "",
"color": null,
"width": "",
"widthunit": "meter",
"length": 0,
"lengthunit": "meter",
"pieces": "",
"cutofquantity": "",
"estimatedConsumption": ""
}
var key = $.map(data, function(value, index) {
return index;
});
var value = $.map(data, function(value, index) {
return value;
});
console.log(value)
Please refer to this JSFiddle for a live example.
Because you have length: 0 as one of your properties, jQuery thinks that the object is an array instead of an object.
It then loops over the numerical indexes from 0 to 0 (not inclusive) and generates a zero length array.
Here is the alternate if you want to use with length:0
var data = {
"productName": "fsdfsdf",
"productDesc": "",
"category": null,
"categoryName": "",
"style": null,
"styleName": "",
"substyle": null,
"substyleName": "",
"store": null,
"storeName": "",
"stand": null,
"standName": "",
"rack": null,
"rackName": "",
"roll": null,
"rollName": "",
"color": null,
"width": "",
"widthunit": "meter",
"length": 0,
"lengthunit": "meter",
"pieces": "",
"cutofquantity": "",
"estimatedConsumption": ""
};
for(var key in data) {
if(data.hasOwnProperty(key)) {
console.log(key) ;
console.log(data[key]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You could do something like this below:
var data = {
"productName": "fsdfsdf",
"productDesc": "",
"category": null,
"categoryName": "",
"style": null,
"styleName": "",
"substyle": null,
"substyleName": "",
"store": null,
"storeName": "",
"stand": null,
"standName": "",
"rack": null,
"rackName": "",
"roll": null,
"rollName": "",
"color": null,
"width": "",
"widthunit": "meter",
"length": 0,
"lengthunit": "meter",
"pieces": "",
"cutofquantity": "",
"estimatedConsumption": ""
};
var arr = Object.keys(data).map(function(k) { return data[k] });
console.log(arr)
Fiddle to play around: https://jsfiddle.net/u5t4L55g/
Loop through each property of the object and push the key and value in array like below. Hope this will help you.
var data = {
"productName": "fsdfsdf",
"productDesc": "",
"category": null,
"categoryName": "",
"style": null,
"styleName": "",
"substyle": null,
"substyleName": "",
"store": null,
"storeName": "",
"stand": null,
"standName": "",
"rack": null,
"rackName": "",
"roll": null,
"rollName": "",
"color": null,
"width": "",
"widthunit": "meter",
"length": 0,
"lengthunit": "meter",
"pieces": "",
"cutofquantity": "",
"estimatedConsumption": ""
}
var value = [];
var key = [];
for (var property in data) {
key.push(property);
value.push(data[property]);
}
console.log(value)
var key = Object.keys(data).map(function(index, value) { return index });
var value = Object.keys(data).map(function(index, value) { return data[index] });
So it is giving key and value pairs
Related
I'm trying to better understand how to work with nested JSON objects in JavaScript/React.
I am getting data through the GitLab API in the following form:
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},]
I want to loop through all objects(merge requests) in this JSON and create a new array with the merge_user.name.
console.log(merge_requests[0].merge_user.name);
console.log(merge_requests[1].merge_user.name);
The logs above return both the correct values. However, I cannot loop through the JSON to create a new array from the data like this:
const arrTest = [];
for(var i = 0; i < Object.keys(merge_requests).length; i++)
{
var mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
}
The code above leads to the following error: Uncaught (in promise) TypeError: resultData[i].merge_user is null
Here is a picture:
I am currently learning JS coming from R. I have huge problems working with JSON instead of dataframes and I cannot find any documentation to learn from. I would appreciated any advice/ sources.
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user?.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
merge_requests[i].merge_user?.name will return undefined if object is not present in the json.
There is no need to use Object.keys(),you can use merge_requests.length directly
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
}]
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
I copy & pasted your code & JSON and it works fine.
Make sure your JSON is parsed after getting it from ate API typeof merge_requests should return object, if it returns string then do the following:
const parsedData = JSON.parse(merge_requests) and loop through parsedData
i checked your code it's working fine.
Check your api request, are you sure you waiting for it till it get fulfilled?
Quick Question:
Pardon me, I'm fairly new to Typescipt & RxJS. I have the following JSON:
[
{
"ID": "",
"UEN": "",
"Name": "",
"Address": "",
"Telephone": "",
"Fax": "",
"Email": "",
"Website": "",
"Postal": "",
"Status": ,
"TimeCreated": ,
"TimeUpdated": ,
"Workheads": [{
"ID": "",
"Name": "",
"Code": ""
},
{
"ID": "",
"Name": "",
"Code": ""
}
]
},
...
]
This json is feed into my angular app via Observable from HTTP get().
How do I filter the workhead.Code section such that I could get those relevant Json objects within the array by matching the inner workhead.Code to a specific string that has been provided by the user (e.g. workhead.Code == 'CS2230')?
Help appreciated.
You are not clear exactly what you want returned. I assume you want the full objects returned, and not only the inner "Workheads". You can use a filter() to get what you want:
const data = [{
"ID": "",
"UEN": "",
"Name": "",
"Address": "",
"Telephone": "",
"Fax": "",
"Email": "",
"Website": "",
"Postal": "",
"Status": "",
"TimeCreated": "",
"TimeUpdated": "",
"Workheads": [{
"ID": "",
"Name": "",
"Code": "abc"
}, {
"ID": "",
"Name": "",
"Code": "def"
}]
}];
// Returns an array of the objects which contain matching code.
const getRelatedByCode = (arr, userProvidedCode) => {
return arr.filter((i) => {
return (i.Workheads || [])
.some(wh => wh.Code === userProvidedCode);
});
}
console.log(getRelatedByCode(data, 'abc')); // Returns array with the object
console.log(getRelatedByCode(data, 'zzz')); // Returns empty array
I'm trying to take this array of arrays,
const parsedCsvData = [
[
"Passage",
"Percentage of",
"constraint2",
"1",
"2",
"",
"",
"",
"",
"",
"",
""
],
[
"",
"",
"",
"",
"",
"",
"",
"",
"Avg A Param",
"",
"0.3",
"0.9"
],
[
"Item",
"Include",
"constraint1",
"1",
"4",
"",
"",
"",
"",
"",
"",
""
],
[
"",
"",
"",
"",
"",
"",
"",
"",
"Item Identifier",
"I105_15201",
"",
""
]
]
and populate this object with their values
const template = {
"attributeName": "",
"constraintType": "",
"objectType": "",
"filters": [
{
"objectType": "",
"attributeName": "",
"values": "",
"valueLowerBound": "",
"valueUpperBound": ""
}
],
"upperBound": "",
"description": "",
"lowerBound": ""
}
each array from parsedCsvData was a row in a CSV file I parsed. Each value in the array of arrays is indexed based off another array
const csvHeaders = [
"objectType",
"constraintType",
"description",
"lowerBound",
"upperBound",
"attributeName",
"referenceValue",
"scope",
"filters",
"values",
"valueLowerBound",
"valueUpperBound"
]
For example, in the first sub array of parsedCsvData Passage is at index 0 and the value for objectType in csvHeaders. Similarly, description is at index 2 and is constraint1 and constraint2 respectively.
Additionally, if there exists a filters value at index 8 in the csv a new row was created. After parsing, this created a new sub array for each filter value. However, each filters value and the following three, values, valueLowerBound and valueUpperBound belong in the same template object as a subarray under the filters key.
Here is an example of the output I am trying to accomplish given what I posted above. Never mind the empty key/value pairs.
[{
"constraintType": "Percentage of",
"objectType": "Passage",
"filters": [
{
"attributeName": "Avg A Param",
"values": "",
"valueLowerBound": "0.3",
"valueUpperBound": "0.9"
} // there may be multiple filter objects as part of this array
],
"upperBound": "2",
"description": "constraint2",
"lowerBound": "1"
},
{
"constraintType": "Include",
"objectType": "Item",
"filters": [
{
"attributeName": "Item Identifier",
"values": "I105_15201",
"valueLowerBound": "",
"valueUpperBound": ""
}
],
"upperBound": "4",
"description": "constraint1",
"lowerBound": "1"
}
]
I've tried mapping the csvHeaders array, attempting to use their indices and then do a map of the the parsedCsvData values and assign them to the template object, but can't seem to get it to work. Any help would be much appreciated.
An approach by checking the first element of the nested arra for either assign a new object or assign a new nested object.
const
parsedCsvData = [["Passage", "Percentage of", "constraint2", "1", "2", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "Avg A Param", "", "0.3", "0.9"], ["Item", "Include", "constraint1", "1", "4", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "Item Identifier", "I105_15201", "", ""]],
template = ["objectType", "constraintType", "description", "lowerBound", "upperBound", "xxxx", "referenceValue", "scope", "attributeName", "values", "valueLowerBound", "valueUpperBound"],
result = parsedCsvData.reduce((r, a) => {
const
assign = (object, target, value) => {
const
keys = target.split('.'),
last = keys.pop();
keys.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
};
if (a[0]) {
r.push(a.reduce((t, v, i) => {
if (v) assign(t, template[i], v);
return t;
}, {}));
} else {
r[r.length - 1].filters = r[r.length - 1].filters || [];
r[r.length - 1].filters.push(a.reduce((t, v, i) => {
if (v) assign(t, template[i], v);
return t;
}, {}));
}
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
below is my JSON
{
"portfolioID": 3024,
"gridType": "OWNER",
"gridLayoutId": 4,
"totalRecordCount": 111,
"attributeMetaData": [
{
"attributeId": 94,
"attributeName": "OWNERTYPE",
"objectType": "OWNER",
"filterValue1": "",
"filterValue2": "",
"filterOperator1": "",
"filterOperator2": "",
"columnSortOrder": 0,
"sortType": "",
"attributeDisplayName": "TYPE",
"columnOrder": 1,
"isGeneralAttribute": "true",
"isIndustryAttribute": "",
"isCustomerAttribute": "",
"dataSource": "Pega",
"isHidden": "false",
"isActionable": "",
"actionType": "",
"referenceAttribute": "",
"attributeDataType": "STRING",
"columnWidth": "",
"isFreezable": ""
},
{
"attributeId": 95,
"attributeName": "OWNERSTATUS",
"objectType": "OWNER",
"filterValue1": "",
"filterValue2": "",
"filterOperator1": "",
"filterOperator2": "",
"columnSortOrder": 0,
"sortType": "",
"attributeDisplayName": "STATUS",
"columnOrder": 2,
"isGeneralAttribute": "true",
"isIndustryAttribute": "",
"isCustomerAttribute": "",
"dataSource": "Pega",
"isHidden": "false",
"isActionable": "",
"actionType": "",
"referenceAttribute": "",
"attributeDataType": "STRING",
"columnWidth": "",
"isFreezable": ""
},
{
"attributeId": 93,
"attributeName": "PREFERREDNAME",
"objectType": "OWNER",
"filterValue1": "",
"filterValue2": "",
"filterOperator1": "",
"filterOperator2": "",
"columnSortOrder": 1,
"sortType": "ASC",
"attributeDisplayName": "LICENSE OWNER NAME",
"columnOrder": 3,
"isGeneralAttribute": "true",
"isIndustryAttribute": "",
"isCustomerAttribute": "",
"dataSource": "Pega",
"isHidden": "false",
"isActionable": "true",
"actionType": "VIEWPAGE",
"referenceAttribute": "LICENSEOWNERID",
"attributeDataType": "STRING",
"columnWidth": "",
"isFreezable": ""
},
{
"attributeId": 115,
"attributeName": "LICENSEOWNERID",
"objectType": "OWNER",
"filterValue1": "",
"filterValue2": "",
"filterOperator1": "",
"filterOperator2": "",
"columnSortOrder": 0,
"sortType": "",
"attributeDisplayName": "LICENSEOWNERID",
"columnOrder": 0,
"isGeneralAttribute": "true",
"isIndustryAttribute": "",
"isCustomerAttribute": "",
"dataSource": "Pega",
"isHidden": "true",
"isActionable": "",
"actionType": "",
"referenceAttribute": "",
"attributeDataType": "INTEGER",
"columnWidth": "",
"isFreezable": ""
}
],
"attributeValues": [
{
"objectId": 133218,
"attributeList": [
{
"attributeId": 94,
"attributeValue": "Entity",
"referenceObjectId": null
},
{
"attributeId": 95,
"attributeValue": "Active",
"referenceObjectId": null
},
{
"attributeId": 93,
"attributeValue": null,
"referenceObjectId": "133218"
},
{
"attributeId": 115,
"attributeValue": "133218",
"referenceObjectId": null
}
]
},
{
"objectId": 134179,
"attributeList": [
{
"attributeId": 94,
"attributeValue": "Individual",
"referenceObjectId": null
},
{
"attributeId": 95,
"attributeValue": "Active",
"referenceObjectId": null
},
{
"attributeId": 93,
"attributeValue": "Ra vi Teja",
"referenceObjectId": "134179"
},
{
"attributeId": 115,
"attributeValue": "134179",
"referenceObjectId": null
}
]
}
]
}
Tried below JS
data.attributeValues.forEach((item, i) => {
const itemattrId = item.attributeList[i].attributeId;
data.attributeMetaData.forEach((subItem, j) => {
const subitemattrId = subItem.attributeId;
if (itemattrId === subitemattrId) {
console.log(subItem.attributeName + ' - ' + item.attributeList[i].attributeValue);
}
});
});
I want to loop through this JSON to get the mapping of column name and column values. In the JSON the mapping is done by the property called 'attributeId'. in 'attributeMetaData', 'attributeName' is the name of the column and in 'attributeValues', there is multiple 'attributeList' and in each of them have the 'attributeId' and 'attributeValue' properties. Actually I am trying to build an object to proper name value pairs to bind it to a grid. So, based on 'attributeId', I wanted to map each name value pairs. Any help would be greatly appreciated. Thanks.
const idToNameMap = {};
obj.attributeMetaData.forEach(item => {
idToNameMap[item.attributeId] = item;
})
const rows = obj.attributeValues.map(attributeObj => {
const row = { objectId: attributeObj.objectId };
attributeObj.attributeList.forEach(attr => {
if (idToNameMap[attr.attributeId].isHidden !== "true") {
row[idToNameMap[attr.attributeId].attributeName] = attr.attributeValue;
}
});
return row;
});
console.log(rows); //Prints:
//[
// {
// objectId: 133218,
// OWNERTYPE: 'Entity',
// OWNERSTATUS: 'Active',
// PREFERREDNAME: null,
// },
// {
// objectId: 134179,
// OWNERTYPE: 'Individual',
// OWNERSTATUS: 'Active',
// PREFERREDNAME: 'Ra vi Teja',
// }
//]
I have an object that I would like to filter it's keys..
Im trying to filter the object by an ID, like so:
let myKeys = Object.keys(data).filter(function(key) {
//console.log(data[key]);
if(parseInt(key) === parseInt(vm.system_id)) {
return data[key];
}
});
console.log(myKeys);
This works, partialy - im getting the key, however, im not getting all the data/items under this item im filtering out
The object im filtering is one similar to this one:
{
"646": [{
"id": 52144,
"timestamp": "2017-08-17T14:10:23Z",
"type": "alarm",
"code": 210,
"title": "",
"description": "",
"remedy": "",
"appeared": "2017-08-17T14:10:09Z",
"disappeared": null,
"acknowlegded": null,
"solved": null,
"system_name": "CG-MX19D7K5C1",
"system_id": 646,
"system_device_id": 458,
"stream": "cu351.alarm_code"
}
],
"693": [{
"id": 51675,
"timestamp": "2017-08-16T13:59:55Z",
"type": "alarm",
"code": 215,
"title": "",
"description": "",
"remedy": "",
"appeared": "2017-08-16T13:59:57Z",
"disappeared": null,
"acknowlegded": null,
"solved": null,
"system_name": "Demo 07122016",
"system_id": 693,
"system_device_id": 371,
"stream": "cu351.alarm_code"
}, {
"id": 51677,
"timestamp": "2017-08-16T13:59:57Z",
"type": "alarm",
"code": 214,
"title": "",
"description": "",
"remedy": "",
"appeared": "2017-08-16T13:59:59Z",
"disappeared": null,
"acknowlegded": null,
"solved": null,
"system_name": "Demo 07122016",
"system_id": 693,
"system_device_id": 371,
"stream": "cu351.alarm_code"
}
]
}
Array#filter is expecting a boolean value as return value, you might use this
let myKeys = Object.keys(data).filter(key => key == vm.system_id);
for getting the keys and then render a new object with the given keys.
To get all items in a single array, you could collect them with
let result = myKeys.reduce((r, k) => r.concat(data[k]), []);