Convert array of objects into lowercase - javascript

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);

Related

Unable to update a JSON value

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.

How to remove empty object in array?

I am trying to remove the empty object {} from the below structure.
data = [{
"total" : "value",
"status" : "statusVal",
"recs" : [{
"total" : "value",
"region" : "name",
"recs" : [{},{
"recs" : [{
"recs" : [{
"value" : "a",
"label" : "fn"
}]
}]
}]
}]
}]
This is my JavaScript code where I process the data and trying to remove the empty object from the result.
var result = json.parse(data);
for(var i=0;i<result.length;i++){
if(result[i].hasOwnProperty("recs")){
var fset = result[i].recs;
for(var j=0;j<fset.length;j++){
if(fset[j].recs === undefined || fset[j].recs === null){
delete fset[j].recs;
}
if(fset[j].hasOwnProperty("recs")){
var sset = fset[i].recs;
for(var k=0;k<sset.length;k++){
var tset = sset[i].recs;
if(sset[k].hasOwnProperty("recs")){
for(var z=0;z<tset.length;z++){
if(tset[z].hasOwnProperty("recs")){
// logic to push
}
}
}
}
}
}
}
}
I tried checking null and undefined and also with property check bool as false. Since the empty {} is always returning length as 1, that is also ruled out. I am stuck here on processing the removal of empty object.
Above code is removing the entire recs node. Can you help me find what I am missing?
Check the length of the Object.keys() to see if object is empty or not.
Object.keys(fset[j].recs).length === 0
You can't iterate all the dynamic levels of array manually, so better to write the function which has recursive function call.
var data = [{
"total": "value",
"status": "statusVal",
"recs": [{
"total": "value",
"region": "name",
"recs": [{}, {
"recs": [{
"recs": [{
"value": "a",
"label": "fn"
}]
}]
}]
}]
}]
function removeEmpty(ary) {
ary.forEach((item, index) => {
if (Object.keys(item).length === 0) { ary.splice(index, 1); }
else if (item.recs && item.recs.length > 0)
removeEmpty(item.recs)
});
}
removeEmpty(data)
console.log(data)

How to push values to an object from inside a map function when a condition is met?

How can we push values to an object from inside a map function and return that single object. I have string comparison condition inside the map function. I tried using Object.assign but it returns an array with multiple object inside that array. Instead of this multiple object I'm expecting a single object inside an array.
Map function
let arrayObj = arrayToTraverse.map(function(item) {
var myObj = {};
if(item.inputvalue === 'Name'){
Object.assign(myObj, {name: item.value});
} else if (item.inputvalue === 'Email'){
Object.assign(organizerInfo, {email: item.value});
} else if (item.inputvalue === 'Company'){
Object.assign(organizerInfo, {company: item.value});
}
return myObj;
});
console.log("The array object is", arrayObj)
This return the array of objects as follows
[
{
"name": "Tom"
},
{
"email": "tom#abc.com"
},
{
"company": "ABC"
}
]
But The array I'm expecting is
[
{
"name": "Tom",
"email": "tom#abc.com",
"company": "ABC"
}
]
// or
[
"returned": {
"name": "Tom",
"email": "tom#abc.com",
"company": "ABC"
}
]
An example of arrayToTraverse can be considered as following
[
{
"id": "1",
"inputvalue": "Name",
"value": "Tom",
"type": "Short Text"
},
{
"id": "2",
"inputvalue": "Email",
"value": "tom#abc.com",
"type": "Email ID"
},
{
"id": "3",
"inputvalue": "Company",
"value": "Google",
"type": "Long Text"
}
]
Simply put, you're trying to reduce an array to a single object, not map one array to another.
var arrayToTraverse = [
{inputvalue:"Name",value:"Tom"},
{inputvalue:"Email",value:"tom#abc.com"},
{inputvalue:"Company",value:"ABC"},
{inputvalue:"Foo",value:"Bar"} // wont show up
];
var valuesRequired = ["Name","Email","Company"];
var result = arrayToTraverse.reduce( (acc, item) => {
if(valuesRequired.includes(item.inputvalue))
acc[item.inputvalue.toLowerCase()] = item.value;
return acc;
}, {});
console.log(result);
Edit: Added lookup array for required fields.

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