Unable to update a JSON value - javascript

I'm writing a code where I need to filter a JSON array and update a value of a key. Here is my code.
var data = [{
"Id": "1",
"ab": '123',
"afb_Educational_expense_types_for_school__c": "Books or supplies"
}, {
"Id": "2",
"ab": '343',
"afb_Educational_expense_types_for_school__c": "Mandatory fees"
}, {
"Id": "3",
"ab": '34',
}];
var itemVar = data.filter(item => item.Id == '3');
itemVar['ab'] = '22';
console.log(itemVar);
Here I'm trying to set 'ab' to 22 but it is not working. Where am I going wrong?

Your itemVar is an array, because .filter always returns an array. You have to specify that you want the first element in the array [0]
itemVar[0]['ab'] = '22';

You can use findIndex and then update the relevant item of the array:
const data = [
{ "Id": "1", "ab": '123', "afb_Educational_expense_types_for_school__c": "Books or supplies" },
{ "Id": "2", "ab": '343', "afb_Educational_expense_types_for_school__c": "Mandatory fees" },
{ "Id": "3", "ab": '34' }
];
let index = data.findIndex((item) => item.Id == '3');
if (index !== -1) data[index].ab = '22';
console.log(data);

var itemVar = data.find((item) => item.Id == '3')
itemVar.ab = '22'
Thats the easiest way to solve it.

Related

Match array values and create final array - Javascript

I have below array. First object is the original data. Inside array is the changed value. I am trying to create a final data by matching with the Name field with inside array. which should look like
var a =
[
{"Id":"1","Test":"Name1","Name":"hunt9988ggggggggggggdfsf1111"},
{"Id":"2","Test":"Name2","Name":"hunt9988ggggggggggggdfsf"},
[
**{"Name":"hunt9988ggggggggggggdfsf1118","Id":"1"}, // Changed value
{"Name":"hunt9988ggggggggggggdfsf1118","Id":"2"}**
]
]
Final Data
var a =
[
{"Id":"1","Test":"Name1","Name":"hunt9988ggggggggggggdfsf1118"},
{"Id":"2","Test":"Name2","Name":"hunt9988ggggggggggggdfsf1118"}
]
I am trying with below code
var result = a.map(item => ({ value: item.Id, text: item.Name}));
console.log(result)
Like this?
Note I modify the original array
let a = [{
"Id": "1",
"Test": "Name1",
"Name": "hunt9988ggggggggggggdfsf1111"
},
{
"Id": "2",
"Test": "Name2",
"Name": "hunt9988ggggggggggggdfsf"
},
[{
"Name": "hunt9988ggggggggggggdfsf1118",
"Id": "1"
}, // Changed value
{
"Name": "hunt9988ggggggggggggdfsf1118",
"Id": "2"
}
]
]
const replaceArray = a.find(item => Array.isArray(item))
replaceArray.forEach(item => a.find(aItem => aItem.Id === item.Id).Name=item.Name)
a = a.filter(item => item.Id)
console.log(a)

Iterating a Json object and storing the end result

I am trying to iterate a JSON object which is an array of categories.The categories may or may not have the subcategory.
If
hasSubcategory = false ,
then category id should be stored in final array.
If hasSubcategory = true ,it should iterate until the subcategory becomes hasSubcategory = false and store id in
final array.
There is parentId field to represent the parent category of the category.
More Importantly there may be sub categories for a single sub category
The final array should only be have the id of categories with hasSubcategory = false .
I would advise to chain filter + map methods:
const arr = [
{
"_id": "1",
"name": "DESKTOP COMPUTERS",
"hasSubCategory": "true",
"parentId": "0"
},
{
"_id": "2",
"name": "LAPTOP COMPUTERS",
"hasSubCategory": "false",
"parentId": "1"
},
{
"_id": "3",
"name": "MONITORS",
"hasSubCategory": "false",
"parentId": "2"
},
{
"_id": "4",
"name": "INPUT DEVICES",
"hasSubCategory": "true",
"parentId": "0"
},
{
"_id": "5",
"name": "PRINTERS SCANNERS",
"hasSubCategory": "false",
"parentId": "4"
},
{
"_id": "6",
"name": "ACCESSORIES",
"hasSubCategory": "false",
"parentId": "4"
},
];
const result = arr.filter(el => el.hasSubCategory === 'false').map(el => el._id);
console.log(result);
This is really simple - just use filter to extract the items with hasSubCategory of false, then map out the _id:
const arr = [{"_id":"1","name":"DESKTOP COMPUTERS","hasSubCategory":"true","parentId":"0"},{"_id":"2","name":"LAPTOP COMPUTERS","hasSubCategory":"false","parentId":"1"},{"_id":"3","name":"MONITORS","hasSubCategory":"false","parentId":"2"},{"_id":"4","name":"INPUT DEVICES","hasSubCategory":"true","parentId":"0"},{"_id":"5","name":"PRINTERS SCANNERS","hasSubCategory":"false","parentId":"4"},{"_id":"6","name":"ACCESSORIES","hasSubCategory":"false","parentId":"4"}];
const res = arr.filter(({ hasSubCategory }) => hasSubCategory == "false").map(({ _id }) => _id);
console.log(res);
For a more efficient solution, use reduce:
const arr = [{"_id":"1","name":"DESKTOP COMPUTERS","hasSubCategory":"true","parentId":"0"},{"_id":"2","name":"LAPTOP COMPUTERS","hasSubCategory":"false","parentId":"1"},{"_id":"3","name":"MONITORS","hasSubCategory":"false","parentId":"2"},{"_id":"4","name":"INPUT DEVICES","hasSubCategory":"true","parentId":"0"},{"_id":"5","name":"PRINTERS SCANNERS","hasSubCategory":"false","parentId":"4"},{"_id":"6","name":"ACCESSORIES","hasSubCategory":"false","parentId":"4"}];
const res = arr.reduce((a, { hasSubCategory, _id }) => (hasSubCategory == "false" ? a.push(_id) : a, a), []);
console.log(res);
Filter first to get the objects you need, then map them into the pattern you need.
let arr = [{"_id":"1","name":"DESKTOP COMPUTERS","hasSubCategory":"true","parentId":"0"},{"_id":"2","name":"LAPTOP COMPUTERS","hasSubCategory":"false","parentId":"1"},{"_id":"3","name":"MONITORS","hasSubCategory":"false","parentId":"2"},{"_id":"4","name":"INPUT DEVICES","hasSubCategory":"true","parentId":"0"},{"_id":"5","name":"PRINTERS SCANNERS","hasSubCategory":"false","parentId":"4"},{"_id":"6","name":"ACCESSORIES","hasSubCategory":"false","parentId":"4"}];
res = arr.filter(v => v.hasSubCategory === "false").map(e => Number(e._id))
console.log(res) // [ 2, 3, 5, 6 ]
Alternatively you can use reduce too:
let arr = [{"_id":"1","name":"DESKTOP COMPUTERS","hasSubCategory":"true","parentId":"0"},{"_id":"2","name":"LAPTOP COMPUTERS","hasSubCategory":"false","parentId":"1"},{"_id":"3","name":"MONITORS","hasSubCategory":"false","parentId":"2"},{"_id":"4","name":"INPUT DEVICES","hasSubCategory":"true","parentId":"0"},{"_id":"5","name":"PRINTERS SCANNERS","hasSubCategory":"false","parentId":"4"},{"_id":"6","name":"ACCESSORIES","hasSubCategory":"false","parentId":"4"}];
res = arr.reduce((a,c) => {if (c.hasSubCategory === "false") a.push(Number(c._id)); return a;}, [])
console.log(res)

Convert array of objects into lowercase

Array looks like this:
"myTags":
[{
"type":"one",
"value":"Testing",
"note":"Hey"
},{
"type":"two",
"value":"Yg5GE",
"note":"hey2"
}]
I need to convert type:'one' value 'Testing' into lowercase i.e. value = Testing needs to be 'testing'. Is there a way to so this keeping the same structure?
Note: "type":"one","value":"Testing", may not always be included in the array. So I guess in this scenario I first need to do a check if they exist?
I have tried .map, however I am unable to get the result I want. Any help would be appreciated.
Ideal structure:
"myTags":
[{
"type":"one",
"value":"testing",
"note":"hey"
},{
"type":"two",
"value":"Yg5GE",
"note":"hey2"
}]
Iterate over the elements in myTags, check if type is "one" and only then change the content of value to lowercase (if present)
var data = {
"myTags": [{
"type": "one",
"value": "Testing",
"note": "Hey"
}, {
"type": "one",
"note": "Hey"
}, {
"type": "two",
"value": "Yg5GE",
"note": "hey2"
}]
};
data.myTags.forEach(function(tag) {
if (tag.type === "one" && typeof tag.value !== "undefined") {
tag.value = tag.value.toLowerCase();
}
});
console.log(data.myTags);
You may also first filter the content of myTags to get the element(s) with "type": "one" and only iterate over those element(s)
var data = {
"myTags": [{
"type": "one",
"value": "Testing",
"note": "Hey"
}, {
"type": "one",
"note": "Hey"
}, {
"type": "two",
"value": "Yg5GE",
"note": "hey2"
}]
};
data.myTags
.filter(function(tag) {
return tag.type === "one";
})
.forEach(function(tag) {
if (typeof tag.value !== "undefined") {
tag.value = tag.value.toLowerCase();
}
});
console.log(data.myTags);
This one works perfectly
$(document).ready(function(){
var objects ={"myTags":
[{"type":"one","value":"Testing", "note":"Hey"}
,{ "type":"two", "value":"Yg5GE", "note":"hey2"}]};
var obj = objects.myTags.map(function(a) {
a.value = a.value.toLowerCase();
return a;
});
console.log(obj);
});
output:
{type: "one", value: "testing", note: "Hey"}
{type: "two", value: "yg5ge", note: "hey2"}
Thank you
Achieve this very simply by using an arrow function and the map() method of the Array
var words = ['Foo','Bar','Fizz','Buzz'].map(v => v.toLowerCase());
console.log(words);

lodash filter by single value and value in array

I have a quick and easy function that I need to use lodash for.
let obj =
{
"AttributeID": "1",
"KeyID": "0",
"Value": "Undefined",
"MetaInsertUtc": "2017-09-13T01:52:22.280"
},
{
"AttributeID": "1",
"KeyID": "1",
"Value": "Tier 1",
"MetaInsertUtc": "2017-09-13T01:52:22.280"
}, {
"AttributeID": "1",
"KeyID": "2",
"Value": "Tier 2",
"MetaInsertUtc": "2017-09-13T01:52:22.280"
}, {
"AttributeID": "1",
"KeyID": "3",
"Value": "Tier 3",
"MetaInsertUtc": "2017-09-13T01:52:22.280"
}, {
"AttributeID": "1",
"KeyID": "4",
"Value": "Tier 4",
"MetaInsertUtc": "2017-09-13T01:52:22.280"
}
let parent = 1;
let children = ['1', '2', '3', '4'];
let test = _.filter(obj, function(item) {
return parseInt(item.AttributeID) === parent && parseInt(item.KeyID) IN[Children];
})
I am trying to filter my objects by a specific parent ID and within those results, find all those that have KeyID that are in our children array.
Update:
Here is my end result based on the selected answer. If there is a more shorthand way to do this by chaining some of these lodash methods together, let me know.
let valueObj = {
"id" : "1",
"name": "Joe"
},
{
"id" : "2",
"name": "Bob"
}
let selectedValues = _.map(valueObj, 'id');
let result = _.filter(obj, function(item) {
return item.AttributeID === attributeID && _.includes(selectedValues, item.KeyID);
});
Use lodash#includes method. If children array contains string values, you shouldn't convert item.KeyID to a number, just compare two strings:
let test = _.filter(obj, function(item) {
let attrId = parseInt(item.AttributeID);
return attrId === parent && _.includes(children, item.KeyID);
});
Assuming your obj is actually an array.
object.filter(item => {
return parseInt(item['AttributeID']) === parent && children.indexOf(parseInt(item['AttributeID'])) > -1;
});
You can do this simple filtering in regular JS.

convert integer to array of object.

var items = [
{ "id": 1, "label": "Item1" },
{ "id": 2, "label": "Item2" },
{ "id": 3, "label": "Item3" }
];
I have this array of objects named 'items'. I get itemselected = 3 from the database.
I need to convert this 3 into the following form.
0:Object
id:3
label:"Item3"
Similarly, if i have a value 2 coming from the database, i should convert it to
0:Object
id:2
label:"Item2"
Can anyone please let me hint of how to get it solved. i am not here to get the answer. These questions are quite tricky for me and i always fail to get the logic right. Any advice on how to master this conversions will be of great help. thanks.
Since you tagged underscore.js, this should be very easy:
var selectedObject = _.findWhere(items, {id: itemselected});
Using ECMA6, you can achieve the same using .find method on arrays:
let selectedObject = items.find(el => el.id === itemselected);
With ECMA5, you can use filter method of arrays. Be careful that filter returns undefined if no element has been found:
var selectedObject = items.filter(function(el) { return el.id === itemselected});
Use jquery $.map function as below
$.map(item, function( n, i ) { if(n["id"] == 3) return ( n );});
Based on the title of your question: «convert integer to array of object». You can use JavaScript Array#filter.
The filter() method creates a new array with all elements that
pass the test implemented by the provided function.
Something like this:
var items = [{
"id": 1,
"label": "Item1"
},
{
"id": 2,
"label": "Item2"
},
{
"id": 3,
"label": "Item3"
}
];
var value = 2;
var result = items.filter(function(x) {
return x.id === value;
});
console.log(result); // Prints an Array of object.
Try this
var obj = {} ;
items = [
{ "id": 1, "label": "Item1" },
{ "id": 2, "label": "Item2" },
{ "id": 3, "label": "Item3" }
];
items.map(function(n) { obj[n.id] = n });

Categories

Resources