AngularJs - Adding new property to item gives dulpcate values using .indexOf - javascript

I am using the following to check for duplicate values in an array before I add a value:
vm.onGridItemChanged = function (resource) {
if (vm.modifiedItems.indexOf(resource) === -1) {
vm.modifiedItems.push(resource);
}
};
This works great and gives me behaviour I want. However I now have need to add EnglishValue also, so I have changed to:
vm.onGridItemChanged = function (resource, englishText) {
var modifiedItem = {Resource: resource, EnglishValue: englishText};
if (vm.modifiedItems.indexOf(modifiedItem) === -1) {
vm.modifiedItems.push(modifiedItem);
}
};
However this breaks the functionality and I am now getting duplicate values? Why would this be the case?
Edit - my josn includes $$hashKey values that is still causing duplicate issues:
[
{
"Resource": {
"ResourceId": "Account_AccountVerified_Success_Title",
"LocaleId": "de",
"ResourceSet": "/WebResources",
"Value": "Erfolg55",
"Comment": "Success",
"Editing": false,
"$$hashKey": "object:3861"
},
"EnglishValue": "Success",
"$$hashKey": "object:40483"
},
{
"Resource": {
"ResourceId": "Account_AccountVerified_Success_Title",
"LocaleId": "de",
"ResourceSet": "/WebResources",
"Value": "Erfolg55",
"Comment": "Success",
"Editing": false,
"$$hashKey": "object:3861"
},
"EnglishValue": "Success",
"$$hashKey": "object:40488"
}
]

You have to convert the JSON object to string and check its index. Since, you have $$hashkey in your object, you first need to remove that by angular.toJson
vm.onGridItemChanged = function (resource, englishText) {
var modifiedItem = {Resource: resource, EnglishValue: englishText};
var modifiedItems = angular.toJson(vm.modifiedItems);
if (JSON.stringify(modifiedItems).indexOf(JSON.stringify(modifiedItem)) === -1) {
vm.modifiedItems.push(modifiedItem);
}
};
var a = [{'d':'dasdasd','e':'dasdasda'}, {'d':'dasdasd','e':'dada'}];
var b = {'d':'dasdasd','e':'dasdasda'};
var index = JSON.stringify(a).indexOf(JSON.stringify(b));
console.log(index);
See that we get the index of the JSON object that exist in the string. Likewise, index will be -1 if not present on the JSON array.

Related

How create an object with dynamic key and dynamic array value with javascript

I have an json data and I wanna create a new object of it according a specific property of the json data; The value of this dynamic key should be an array and I need to update this array if a similar key founded in json data; But I got this error and I don't know what is my bug index.js:46 Uncaught TypeError: object[fullDate] is not iterable
function createGridObject(data) {
let object = {};
for (const item of data) {
const date = new Date(item.orderInfo.demandTime);
const fullDate = `${date.getFullYear()}-${date.getMonth()}-${date.getDay()}`;
console.log({fullDate});
object = {
...object,
[fullDate]: [...object[fullDate], ...item],
};
}
console.log({object});
}
[
{
"id": "2c68be90-6186-44ef-a963-4b5f36d9afe4",
"orderInfo": {
"partNumber": "YDN2ZEP279P1",
"type": "FULL",
"origin": "SU-H40V1",
"destination": "41A01L-T1",
"demandTime": "2021-04-13T21:07:01.587440Z",
"externalOrderId": "181788528",
"containerType": "VW0001",
"received": "2021-04-13T21:02:02.567298Z",
"trailerPosition": null
},
},
{
"id": "1460b736-d6f5-4187-8acc-74f748c8197a",
"orderInfo": {
"partNumber": "",
"type": "EMPTY",
"origin": "SU-H40V1",
"destination": "42A05L-T1",
"demandTime": "2021-04-13T22:27:21.099507Z",
"externalOrderId": "891755586",
"containerType": "VW0001",
"received": "2021-04-13T22:22:24.268943Z",
"trailerPosition": null
}
},
]
If object[fullDate] doesn't exist, [...object[fullDate], ___] is trying to use iterable spread on undefined. You can't do that. (People sometimes get confused, because you can use object property spread on undefined. But not iterable spread.)
Instead:
object = {
...object,
[fullDate]: [...object[fullDate] ?? [], ...item],
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^
};
That way, if it's undefined, you'll spread [] instead.
Or use a conditional:
object = {
...object,
[fullDate]: object[fullDate] ? [...object[fullDate], ...item] : [...item],
};

How to convert JSON string having multiple rows to single row using javascript function

I have an output of REST API in following JSON format:
I need to convert the format to flat format so it can be passed as input to another API call.
{
"result": {
"data": [
{
"data": 2.824315071105957,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationForwardBrakingId" },
"controller": "ControllerNoneId",
"version": "00000000000363b0",
"id": "a5UyPzhknSC-N2wtLBph3BA"
},
{
"data": 0,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationSideToSideId" },
"controller": "ControllerNoneId",
"version": "00000000000363b1",
"id": "a5UyPzhknSC-N2wtLBph3BQ"
},
// ... 1000's of rows like this
]
}
}
I need to convert it in below format using a java-script
Desired format:
{"result":{ "data":[{"id":"b3","dateTime":"2019-09- 10T11:32:05.220Z","DiagnosticAccelerationSideToSideId":0,"DiagnosticAccelerationForwardBrakingId ":2.824315071105957},...
The rows needs to be merged with primary key as combination of ID and dateTime attributes. Please note the diagnostic id value becomes key for the required format and data value is the value of the key.
Is there any way to convert this JSON to above flat format.
Need to convert JSON having many rows for single data entry to single row format. Need one java-script function that can accept a string of rows format and convert or merge it and return the string in desired format
function String mergeRows(String flatDataJSONString) {
...
}
If the items are ordered (meaning i and i+1 are merged) than iterate with jumps of i += 2;
If its not ordered or the amount of items to be merged can be > 2 you use an object with unique key composed of the id and date, and override its data whenever a record match this key:
function merger (jsonStr) {
// convert str to obj
const jsonObj = JSON.parse(jsonStr);
const dataObj = {};
for (let i = 0; i < jsonObj.result.length; i++) {
const item = jsonObj.result[i];
// use unique key to merge by
const itemUniqueKey = item.device.id + item.dateTime;
// take last value or create empty object if not exists
const existingItem = dataObj[itemUniqueKey] || {};
// add some logic to merge item with existingItem as you need
...
// set the result back to dataObj to be used on next merges
dataObj[itemUniqueKey] = [merge result of item and existing item];
}
// take dataObj values, you don't need the keys any more
const dataArr = Object.values(dataObj);
const finalResult = {
result: {
data: dataArr
}
}
// convert back to json
return JSON.stringify(finalResult);
}
As stated in the comment you want first to have a clean json definition in order to stringify it. Please get to the following definition of your JSON first:
const json = {
"result": [
{
"data": 2.824315071105957,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationForwardBrakingId" },
"controller": "ControllerNoneId",
"version": "00000000000363b0",
"id": "a5UyPzhknSC-N2wtLBph3BA"
},
{
"data": 0,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationSideToSideId" },
"controller": "ControllerNoneId",
"version": "00000000000363b1",
"id": "a5UyPzhknSC-N2wtLBph3BQ"
}]
};
and then you will be able to perform like hereafter :
JSON.stringify(json)
Hope this helps !

Javascript using variable as key to get nested object value

Assume I have the following object:
var jsonObj = {
"response":{
"result":{
"status":{
"name": "Eric"
}
}
}
}
And now i'd like to dynamically access a nested property:
jsonKey = "response.result.status.name";
console.log("the status is: " + jsonObj.jsonKey); //I cannot call jsonObj.jsonKey here
Is there any way to achieve this?
You cannot access a deeply nested property as simple as you expect. Instead you need to use the obj[propertyNameAsString] syntax to dive deeper into the response one by one.
This would be one way of getting there:
let response = {
"response": {
"method": "GetStatus",
"module": "Module",
"data": null,
"result": {
"status": {
"name": "Eric"
},
"id": 1
},
"result_code": {
"error_code": 0
}
}
}
let keyString = "response.result.status.name"
let keyArray = keyString.split('.'); // [ "response", "result", "status", "name" ]
var result = response;
for (key of keyArray) {
result = result[key]
}
console.log(result)
Please be aware that this is not failsafe against cases where one of those strings in keyArray does not exist as a property on the preceding object.
You can do like this something['bar']
Where bar is your variable that has been converted to string, in our case:
jsonObj[`${jsonKey}`]

getting a specific value from JSON array with multiple arrays inside in javascript

I'm asking here as I can see this website the most one can help in this
I have an output value in JASON format as the following:
{
"total": 16,
"members": [{
"id": 4,
"name": "Blade11",
"descriptors": {
"os": "Windows 2012 / WS2012 R2"
},
"FCPaths": [{
"wwn": "50060B0000C27208",
"hostSpeed": 0
}, {
"wwn": "50060B0000C2720A",
"hostSpeed": 0
}],
"iSCSIPaths": [],
"persona": 11,
"links": [{
"href": "https://3par:8080/api/v1/hostpersonas?query=\"wsapiAssignedId EQ 11\"",
"rel": "personaInfo"
}],
"initiatorChapEnabled": false,
"targetChapEnabled": false
}, {
"id": 6,
"name": "Blade4",
"descriptors": {
"os": "VMware (ESXi)"
},
"FCPaths": [{
"wwn": "50060B0000C27216",
"hostSpeed": 0
}, {
"wwn": "50060B0000C27214",
"hostSpeed": 0
}],
"iSCSIPaths": [],
"persona": 8,
"links": [{
"href": "https://3par:8080/api/v1/hostpersonas?query=\"wsapiAssignedId EQ 8\"",
"rel": "personaInfo"
}],
"initiatorChapEnabled": false,
"targetChapEnabled": false
}
what I want is, to parse this output for retrieving an output parameter with the name object only in a list or array of string
for example Names = Blade11, Blade4,....
if you can see in the Json output we have all the names under "members", then each one is another array of values, I want to retrieve only names
thanks
If this JSON is string first you have to parse it
var json = JSON.parse('here is your JSON string');
Than you can access to it properties like you work with object
var names = json.members.map(function(member) {
return member.name;
});
Since you already have JSON format, you can use an array method on the member key of your JSON object to iterate through each array item.
var names = [];
object_name.members.forEach((arrItem) => {
names.push(arrItem.name);
}
or
namesArray = object_name.members.map((arrItem) => {
return arrItem.name;
}
You could use Array#map for iterating all elements of the array and return only the name property.
If you have a JSON string, you need to parse it in advance for getting an object, like
object = JSON.parse(jsonString);
var jsonString = '{"total":16,"members":[{"id":4,"name":"Blade11","descriptors":{"os":"Windows 2012 / WS2012 R2"},"FCPaths":[{"wwn":"50060B0000C27208","hostSpeed":0},{"wwn":"50060B0000C2720A","hostSpeed":0}],"iSCSIPaths":[],"persona":11,"links":[{"href":"https://3par:8080/api/v1/hostpersonas?query=\\"wsapiAssignedId EQ 11\\"","rel":"personaInfo"}],"initiatorChapEnabled":false,"targetChapEnabled":false},{"id":6,"name":"Blade4","descriptors":{"os":"VMware (ESXi)"},"FCPaths":[{"wwn":"50060B0000C27216","hostSpeed":0},{"wwn":"50060B0000C27214","hostSpeed":0}],"iSCSIPaths":[],"persona":8,"links":[{"href":"https://3par:8080/api/v1/hostpersonas?query=\\"wsapiAssignedId EQ 8\\"","rel":"personaInfo"}],"initiatorChapEnabled":false,"targetChapEnabled":false}]}',
object = JSON.parse(jsonString),
array = object.members.map(function (a) { return a.name; });
console.log(array);

JavaScript find in json array match key

I have a JSON object that changes as it is appended with other objects throughout my application.
I have created a JavaScript function which behaves like indexOf but for a JSON array.
It looks like this:
// Find via slug
self.findSlug = function (array, slug) {
// Counter
var i = array.length;
// While i
while (i--) {
// If we find our slug, break the loop
if (array[i].slug === slug)
break;
}
// Return our counter
return i;
}
this works fine if the JSON object has a key called "slug". Now I would like to make it abiguous. i.e. something like:
if (array[i]["key-name"] === slug) break;
Here is an example of an array:
[
{
"title": "Hoody",
"price": 10,
"designable": true,
"configurable": true,
"slug": "hoody",
"fabric": "980506857489564534",
"font": "city-bold",
"fabrics": [
]
}
]
but that doesn't appear to work. Can someone suggest a way of doing this?
Cheers,
/r3plica
Please try this:
var array = {
1:{"title": "Hoody", "price": 10,"designable": true,"configurable": true,"slug": "hoody", "fabric": "980506857489564534",
"font": "city-bold", "fabrics": [ ] },
2:{"title": "Hoody2", "price": 20,"designable": true,"configurable": true,"slug": "hoody2", "fabric": "980506857489564534",
"font": "city-bold", "fabrics": [ ] }
}
for (key in array){
for (subkey in array[key]) {
if(subkey=="slug"){
//do something
}
}
}

Categories

Resources