Creating and Updating JSON - javascript

I can create a Json object as here
How to create json by javascript for loop?
great!
and I have created one like below
[
{
"id": "10",
"userName": "kuttan"
},
{
"id": "11",
"userName": "kunjan"
}
]
Suppose I want to update name of the user with id 10 to "new name"
what should i do?(i dont know the index is 1)

Loop over your array of objects (because that's what it is), and check the "id" attribute of each object.
var list = [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ];
for (var i=0;i<list.length;i++) {
if (list[i].id == "10") {
alert(i);
};
};
You could then abstract this into some nice function.
function findIndexById(list, id) {
for (var i=0;i<list.length;i++) {
if (list[i].id == id) {
return i;
};
};
return -1;
};
Then use it as follows:
var list = [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ];
var index = findIndexById(list, "10");
if (index !== -1) {
list[index].userName = "new username";
};

You can loop through the array and check the id property of the object in the current iteration. If it's 10, assign the new username to userName.
var json = [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ],
len = json.length,
obj;
while(len--) {
obj = json[len];
if (obj.id == 10) {
obj.userName = 'foobar';
}
}
console.log(json); // outputs [{id:"10", userName:"foobar"}, {id:"11", userName:"kunjan"}]

Related

IE9: Manipulate a string if the value of the string has a match in an array of Objects

In the below function setChildNumber Strings like 'Child2' or 'Child3', 'Child4' are passed.
'family' variable contains array of object. I've added a sample data. This code needs to support IE9. So I can't use 'find'.
Objective:
I need help finding the index from family array of objects, if
family.type === child and id === memberID, the replace memberID with
index from family[]
function setChildNumber(member) {
var family = JSON.parse(sessionStorage.getItem('memberObject'));
var memberID = +member.match(/\d+/)[0];
if(!family) return;
var index = member.toLowerCase().indexOf('child') === 0
&& family.find(function(elem) {
return (elem.id === memberID);
}).index;
return member.slice(0, member.length-1) + ' ' + index;
}
family = [
{
"id": 1,
"type": "SELF",
"birthday": "10/10/1980",
"age": 40
},
{
"id": 2,
"type": "CHILD",
"index": 1,
"birthday": "10/10/2001"
},
{
"id": 3,
"type": "SPOUSE",
"birthday": "10101980",
"age": 40
},
{
"id": 4,
"type": "CHILD",
"index": 2,
"birthday": "10102010",
"age": 10
}
]
You can use a simple for loop.
var idx = -1;
for(var i = 0; i < family.length; i++){
if(family[i].type.toLowerCase() === 'child' && family[i].id === memberID){
idx = i;
break;
}
}

javascript remove duplicates from array of objects

I have below array of objects,
var parsedData = [
{
"ID": "16",
"DESCRIPTION": "SMAATO"
},
{
"ID": "26",
"DESCRIPTION": "BIDSWITCH"
},
{
"ID": "1572",
"DESCRIPTION": "BIDSWITCH"
}
]
i have removed duplicate from this using below code,
var flags = [], l = parsedData.length, i;
for( i=0; i<l; i++) {
if( flags[parsedData[i].DESCRIPTION]){
if(attribute.toLowerCase() == "supply"){
console.log("coming!!"+parsedData[i].ID+"---"+parsedData[i].DESCRIPTION);
}
continue;
}
flags[parsedData[i].DESCRIPTION] = true;
groups_array.push({
id: parsedData[i].ID,
text: parsedData[i].DESCRIPTION
});
}
but what i need to achive is, if id is differnt and description same means need to append id to first one and remove duplicate one like this,
[
{
"ID": "16",
"DESCRIPTION": "SMAATO"
},
{
"ID": "26,1572",
"DESCRIPTION": "BIDSWITCH"
}
]
How to get this one help me please...
Try:
if (flags[parsedData[i].DESCRIPTION]) {
let id = groups_array.map(item => item.text).indexOf(parsedData[i].DESCRIPTION);
groups_array[id].id = groups_array[id].id + "," + parsedData[i].ID
continue;
}

javascript indexOf does not work with numeric sequence

I'm trying to compare if a string, which I get from a JSON, starts with a certain number, for example if string 1.1.01.10.0001 starts with 1.1.01.10. I wrote this code to test this:
var result = JSON.parse(data);
for (x in result.group){
var group = JSON.stringify(x.group);
for (y in result.account){
var account = JSON.stringify(y.account);
console.log(group);
console.log(account);
if (account.indexOf(group) != -1){
alert("ok");
}
}
}
I do not know where the error is, the console returns this here:
In the first result it should return some number other than -1, how to solve this?
For given JSON, this is working fine
var data = {
"group": [{
"description": "xxxxx",
"group": "1.1.01.10"
}, {
"description": "xxxxx",
"group": "1.1.01.20"
}],
"account": [{
"description": "xxxxx",
"account": "1.1.01.10.001"
}, {
"description": "xxxxx",
"account": "1.1.01.20.001"
}, {
"description": "xxxxx",
"account": "1.1.01.20.002"
}, {
"description": "xxxxx",
"account": "1.1.01.20.003"
}]
}
data = JSON.stringify(data);
var result = JSON.parse(data);
var customFn = function(val) {
for (var x = 0; x < result[val].length; x++) {
var value = result[val][x];
console.log(value[val]);
if (value[val].indexOf('1.1.01.10.') != -1) {
alert("ok value is " + value[val]);
}
}
}
customFn('group');
customFn('account');

Find and replace in nested objects

I'm struggling with the following issue:
I have a nested object. From the server I get a response with an object with changed values. So I want to find the object in my nested object and replace it.
My object has a structure like this:
$scope.page = {
id: 5,
label: 'myPage',
items : [
{
"type": "Container",
"id": 1,
"label": "header",
"items": [
{
"type": "Container",
"id": 2,
"label": "left",
"items": [
{
"type": "Menu",
"label": "settings-menu",
"id": "5"
},
{
"type": "Menu",
"label": "main-menu",
"id": "7"
}
]
},
{
"type": "Container",
"id": 4,
"label": "right",
"items": [
{
"type": "Post",
"label": "contact",
"id": "25"
}
]
}
]
},
{
"type": "Postlist",
"label": "nieuwsberichten",
"id": "17"
},
{
"type": "HTML",
"label": "over deze site",
"id": "18"
},
{
"type": "Other",
"label": "twitter feed",
"id": "19"
}
]
}
From the server I get a new object:
var newItem = {
"type": "Post",
"label": "contact",
"id": "25"
}
How can I update the object inside $scope.page the right way? I've tried the following:
$scope.findAndReplace(newItem,$scope.page.items);
$scope.findAndReplace = function(newItem, items) {
for (var i = 0; i < items.length; i++) {
if (items[i].id == newItem.id) {
items[i] = newItem;
} else if (items[i].items) {
$scope.findAndReplace(newItem, items[i].items);
}
}
}
and:
var oldItem = $scope.findById(item.id, $scope.page.items);
oldItem = newItem;
$scope.findById = function(id, items) {
var match = null;
angular.forEach(items, function(i){
if (match == null) {
if (i.id == id) {
match = i;
} else if (i.items) {
match = $scope.findById(id, i.items)
}
}
})
return match;
}
Neither of these options work. That's because of the nested loops where the object isn't the one in $scope.page anymore.
Anyone an idea to handle this?
Your example looks fine, can't understand why they are not working.
Neither of these options work. That's because of the nested loops where the object isn't the one in $scope.page anymore.
You can keep object reference by using angular.copy(newItem, oldItem)
Hi I have created a fiddle for you.
click for fiddle
for(var indx=0; indx < $scope.page.items.length; indx++) {
var tmpObj = $scope.page.items[indx];
if(tmpObj.hasOwnProperty('items')) {
// check inside
for(var indx1=0; indx1<tmpObj.items.length; indx1++ ) {
var innerObj = tmpObj.items[indx1];
// check for next level
if(innerObj.hasOwnProperty('items')) {
for(var counter=0; counter< innerObj.items.length; counter++) {
var thirdTmp = innerObj.items[counter];
console.log('3rd level inner object', thirdTmp);
if(thirdTmp.id === newItem.id) {
innerObj.items[counter] = newItem;
tmpObj.items[indx1] = innerObj;
$scope.page.items[indx] = tmpObj;
}
}
}
}
} else if(tmpObj.id === newItem.id) {
$scope.page.items[indx] = newItem;
}
};

How to check that object with same ID (or any other attribute ) exists in array of objects?

I have following array:
var array = [
{
"milestoneTemplate": {
"id": "1",
"name": "TEST1"
},
"id": "1",
"date": "1416680824",
"type": "ETA",
"note": "Note",
"color": "66FF33"
},
{
"milestoneTemplate": {
"id": "2",
"name": "Test 2"
},
"id": "2",
"date": "1416680824",
"type": "ATA",
"note": "Note 22",
"color": "66FF00"
}
];
And now i would like to check in forEach loop that object (which is passed in param of the function) is existing in array by his ID.
In case that not = do push into existing array.
arrayOfResults.forEach(function(entry) {
if(entry != existingInArrayByHisId) {
array.push(entry);
}
});
Thanks for any advice
You could create a helper function thats checks if an array contains an item with a matching property value, something like this:
function checkForMatch(array, propertyToMatch, valueToMatch){
for(var i = 0; i < array.length; i++){
if(array[i][propertyToMatch] == valueToMatch)
return true;
}
return false;
}
which you can then use like so:
arrayOfResults.forEach(function (entry) {
if (!checkForMatch(array, "id", entry.id)) {
array.push(entry);
}
});

Categories