Javascript: append single quotes to individual object results - javascript

I have an object with multiple properties, I want to wrap the results in single quotes and commas if there are multiple values please see the following fiddle.
http://jsfiddle.net/efv7sh9d/1/
var obj = {
WKF001: ['test1'],
WKF002: ['test2','test3'],
WKF003: ['test4','test5','test6','test7'],
WKF004: ['test8','test8','test9','test10','test11'],
WKF005: ['test12','test13','test14','test15','test16']
}
function returnCodes(wkf, obj) {
for (var d in obj) {
if (d.indexOf(wkf) > -1) {
return obj[d];
}
}
return 'Unknown';
}
var wkftest1 = "WKF001";
var wkftest2 = "WKF002";
var wkftest3 = "WKF003";
document.write(returnCodes(wkftest3, obj).join("','"));
This will return test4','test5','test6','test7 and I need it to be 'test4','test5','test6','test7'

document.write("'" + returnCodes(wkftest3, obj).join("','") + "'");
This is a common idiom in any language with an array join method/function.

Related

Remove duplicates in array separated by double commas in JavaScript

I have an array in JavaScript like this
var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
when I alert in JavaScript it gives as below
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
But I want like this which is duplicates removed array
var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
On alert it should give like this
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
First Thing your array contains string as a constant that's not going to work.
Secondly, if all of you value are strings you can do it as follows:
var data =[,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV","XIV","V3",,"B_2_XVI","XVI","V3"];
var uniqueArray = data.filter(function(item, pos) {
return data.indexOf(item) == pos;
})
alert(uniqueArray);
Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop:
var data [/* ... */];
var unique_data = [];
for(let i = 0; i < data.length; i++) {
if (data[i] && unique_data.indexOf(data[i]) === -1) {
unique_data.push(data[i]);
}
}
Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf().
You can create your unique function to remove duplicate entry and empty value from array like this.
var data =[,"A_1_VII,VII","V2,,A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV,XIV","V3",,"B_2_XVI,XVI,V3"]
var unique_data = uniqueList(data);
alert(unique_data);
function uniqueList(list) {
var uniqueResult = [];
$.each(list, function(i, e) {
if ($.inArray(e, uniqueResult) == -1 &&$.inArray(e, uniqueResult)!="")// chech for unique value and empty value
uniqueResult.push(e);
});
return uniqueResult ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Matching a string to an array

I need your your help,
For some strange reason, when my var str is set to "OTHER-REQUEST-ASFA" the matched key comes back as "ASF" as opposed to "ASFA"
How can I get the returned output key of "ASFA" when my str is "OTHER-REQUEST-ASFA"
function test() {
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
for (var key in filenames) {
if (str.indexOf(key) != -1) { alert(filenames[key]) }
}
}
You could switch from
str.indexOf(key)
to
key.indexOf(str)
function test() {
var str = "OTHER-REQUEST-ASFA",
filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
},
key;
for (key in filenames) {
if (key.indexOf(str) != -1) {
console.log(filenames[key]);
}
}
}
test();
To answer why it's not working as you want...
You've got:
str.indexOf(key)
This checks for the first instance of key in str.
So in your loop, key first equals OTHER-REQUEST-ASF which is part of OTHER-REQUEST-ASFA, so the condition is true.
However, to do what you want to do, if you know the pattern is always going to be OTHER-REQUEST-XYZ, the easiest way is to use split():
str.split('-')[2]
will always return the last section after the last -
cause "OTHER-REQUEST-ASFA".indexOf("OTHER-REQUEST-ASF") will not return -1, so it will show "ASF"
You can also use static method Object.keys() to abtain array of keys
var test = () =>{
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
Object.keys(filenames).forEach(x => {
if ( x.indexOf(str) !== -1)
console.log(filenames[str]);
});
}
test();

Use underscore to find a value by key

I have a string that I need to search for within a json object and return back a specific hash number from that found value. I got it to work without underscore, but it's poorly optimized. What I need to do is stop the loop as soon as the fileToSearch string is found.
For example, I have a json object here:
var json = {
"images/mike.jpg" : "images/mike.12345.jpg",
"images/joe.jpg" : "images/joe.axcvas.jpg",
"images/mary.jpg" : "images/mary.mndfkndf.jpg",
"images/jane.jpg" : "images/jane.dfad34.jpg",
};
And I have a variable fileToSearch that I need to look for in the above object.
var fileToSearch = "joe.jpg";
What should get outputted is the hash value in images/joe.axcvas.jpg, so axcvas.
Without underscore:
var hash;
for (var key in json) {
var index = key.indexOf(fileToSearch);
if (index !== -1) {
hash = json[key].split('.')[1];
}
}
console.log(hash); //axcvas
How can I optimize/achieve this with Underscore?
You can use _.findKey in such way:
var key = _.findKey(json, function(value, key) {
return key.indexOf(fileToSearch) >= 0;
});
var hash = key? json[key].split('.')[1] : undefined;
Note that this method is available since v1.8.0.
You can break the loop when you find the element
var hash;
for (var key in json) {
var index = key.indexOf(fileToSearch);
if (index !== -1) {
hash = json[key].split('.')[1];
break;
}
}
console.log(hash);

how to delegate this in javascript?

var selValues = {};
selValues['234'] = $('#asd').val();
selValues['343'] = function () { var el = ''; $('#asd input[#type=checkbox]:checked').each(function() { el += $(this).val() + '|'; }); return el; } };
here's the explanation:
im creating a key-value array where it extracts different values from DOM objects. The last array that you see in the example actually tries to extract checked items in a checkbox list. I tried to delegate the loop and return a delimited string of all checked values, but it's not working.
A mapping is probably a better solution here:
var el = $('#asd input:checkbox:checked').map(function(){
return $(this).val();
}).get().join('|');
If I'm understanding your question correctly, the problem you are running up against is that you are merely storing a function in selValues['343'], not evaluating it.
You could try selValues['343'] = function () { var el = ''; $('#asd input[#type=checkbox]:checked').each(function() { el += $(this).val() + '|'; }); return el; } }(); (notice the parentheses at the end) which should evaluate your function and store the result in selValues['343'].
Seems to work for me: http://jsfiddle.net/HM4zD/

Convert an HTML form field to a JSON object with inner objects

Given the following HTML form:
<form id="myform">
Company: <input type="text" name="Company" value="ACME, INC."/>
First Name: <input type="text" name="Contact.FirstName" value="Daffy"/>
Last Name: <input type="text" name="Contact.LastName" value="Duck"/>
</form>
What is the best way serialize this form in javascript to a JSON object in the format:
{
Company:"ACME, INC.",
Contact:{FirstName:"Daffy", LastName:"Duck"}
}
Also note that there might be more than 1 "." sign in the field name.
I think that what you'd do is this: for each input, first split the name at the separators (the '.' characters). Now, you have an array of names. You can then iterate through that array, making sure that your target "assembly" object (and sub-objects) have containers every time you come across a new name segment. When the array has 1 element in it, you simply add the value.
$.fn.extractObject = function() {
var accum = {};
function add(accum, namev, value) {
if (namev.length == 1)
accum[namev[0]] = value;
else {
if (accum[namev[0]] == null)
accum[namev[0]] = {};
add(accum[namev[0]], namev.slice(1), value);
}
};
this.find('input, textarea, select').each(function() {
add(accum, $(this).attr('name').split('.'), $(this).val());
});
return accum;
});
// ...
var object = $('#myform').extractObject();
I just sort-of made that up so there might be a bug or two; I can't remember whether all the browsers have "slice" but I think they do.
(edit: I forgot the all-important call to split())
You can loop through the form fields by name, use String#split to split the names on dot, and build up your resulting structure. Concept code:
function serializeDeep(form) {
var rv, obj, elements, element, index, names, nameIndex, value;
rv = {};
elements = form.elements;
for (index = 0; index < elements.length; ++index) {
element = elements[index];
name = element.name;
if (name) {
value = $(element).val();
names = name.split(".");
obj = rv;
for (nameIndex = 0; nameIndex < names.length; ++nameIndex) {
name = names[nameIndex];
if (nameIndex == names.length - 1) {
obj[name] = value;
}
else {
obj = obj[name] = obj[name] || {};
}
}
}
}
return rv;
}
Note that that doesn't allow for fields with repeated names (which should create arrays), nor does it elegantly handle a situation where you use the names "foo" and "foo.bar". But it should get you started.
I have managed it this way:
$('#Myform').attr('onsubmit', 'test()');
function test() {
var obj = {};
obj.title =$('#title').prop('value');
console.log('title: '+obj.title);
obj.website =$('#website').prop('value');
console.log('website: '+obj.website);
obj.tags =$('#tags').prop('value').split(',');
console.log('tags: '+obj.tags);
do_something(JSON.stringify(obj));
}
Of course this can be done if you know what the names are, and I am in fact generating the table itself using Formation plug-in.
I created an example for this question by using plain js, please check developer tool console to see the data object!
jsfiddle example
var data = {};
var array = 'person.name.first'.split('.');
var value = 'myFirstName';
generateObj(data, array, value);
console.log(data);
function generateObj(obj, arr, val) {
if (arr.length === 1) {
obj[arr[0]] = val
return;
}
var restArr = arr.splice(1);
if (!obj[arr[0]]) {
obj[arr[0]] = {};
}
generateObj(obj[arr[0]], restArr, val);
}
solution:
transform each name string to array.
iterate through each array.
recursively call a method which create an obj and set this obj as the value of the property and pass this obj to the next recursion.
Create an object of that shape then use a JSON encoder to write it out.

Categories