I'm trying to iterate over a "value" list and convert it into a string. Here is the code:
var blkstr = $.each(value, function(idx2,val2) {
var str = idx2 + ":" + val2;
alert(str);
return str;
}).get().join(", ");
alert() function works just fine and displays the proper value. But somehow, jquery's .get() function doesn't get the right sort of object and fails. What am I doing wrong?
If value is not a plain array, such code will work fine:
var value = { "aaa": "111", "bbb": "222", "ccc": "333" };
var blkstr = [];
$.each(value, function(idx2,val2) {
var str = idx2 + ":" + val2;
blkstr.push(str);
});
console.log(blkstr.join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
(output will appear in the dev console)
As Felix mentioned, each() is just iterating the array, nothing more.
Converting From Array to String is So Easy !
var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday']
array = A + ""
That's it Now A is a string. :)
You can use .toString() to join an array with a comma.
var array = ['a', 'b', 'c'];
array.toString(); // result: a,b,c
Or, set the separator with array.join('; '); // result: a; b; c.
not sure if this is what you wanted but
var arr = ["A", "B", "C"];
var arrString = arr.join(", ");
This results in the following output:
A, B, C
Four methods to convert an array to a string.
Coercing to a string
var arr = ['a', 'b', 'c'] + []; // "a,b,c"
var arr = ['a', 'b', 'c'] + ''; // "a,b,c"
Calling .toString()
var arr = ['a', 'b', 'c'].toString(); // "a,b,c"
Explicitly joining using .join()
var arr = ['a', 'b', 'c'].join(); // "a,b,c" (Defaults to ',' seperator)
var arr = ['a', 'b', 'c'].join(','); // "a,b,c"
You can use other separators, for example, ', '
var arr = ['a', 'b', 'c'].join(', '); // "a, b, c"
Using JSON.stringify()
This is cleaner, as it quotes strings inside of the array and handles nested arrays properly.
var arr = JSON.stringify(['a', 'b', 'c']); // '["a","b","c"]'
jQuery.each is just looping over the array, it doesn't do anything with the return value∆. You are looking for jQuery.map (I also think that get() is unnecessary as you are not dealing with jQuery objects):
var blkstr = $.map(value, function(val,index) {
var str = index + ":" + val;
return str;
}).join(", ");
DEMO
But why use jQuery at all in this case? map only introduces an unnecessary function call per element.
var values = [];
for(var i = 0, l = value.length; i < l; i++) {
values.push(i + ':' + value[i]);
}
// or if you actually have an object:
for(var id in value) {
if(value.hasOwnProperty(id)) {
values.push(id + ':' + value[id]);
}
}
var blkstr = values.join(', ');
∆: It only uses the return value whether it should continue to loop over the elements or not. Returning a "falsy" value will stop the loop.
this's my function, convert object or array to json
function obj2json(_data){
str = '{ ';
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += "'" + i + "':" + obj2arr(v) ;
else if ($.type(v)== 'array')
str += "'" + i + "':" + obj2arr(v) ;
else{
str += "'" + i + "':'" + v + "'";
}
});
return str+= '}';
}
i just edit to v0.2 ^.^
function obj2json(_data){
str = (($.type(_data)== 'array')?'[ ': '{ ');
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += '"' + i + '":' + obj2json(v) ;
else if ($.type(v)== 'array')
str += '"' + i + '":' + obj2json(v) ;
else{
if($.type(_data)== 'array')
str += '"' + v + '"';
else
str += '"' + i + '":"' + v + '"';
}
});
return str+= (($.type(_data)== 'array')? ' ] ':' } ');;
}
var arr = new Array();
var blkstr = $.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
return arr;
}).join(', ');
console.log(blkstr);
OR
var arr = new Array();
$.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
});
console.log(arr.join(', '));
convert an array to a GET param string that can be appended to a url could be done as follows
function encodeGet(array){
return getParams = $.map(array , function(val,index) {
var str = index + "=" + escape(val);
return str;
}).join("&");
}
call this function as
var getStr = encodeGet({
search: $('input[name="search"]').val(),
location: $('input[name="location"]').val(),
dod: $('input[name="dod"]').val(),
type: $('input[name="type"]').val()
});
window.location = '/site/search?'+getStr;
which will forward the user to the /site/search? page with the get params outlined in the array given to encodeGet.
Here's an example using underscore functions.
var exampleArray = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var finalArray = _.compact(_.pluck(exampleArray,"name")).join(",");
Final output would be "moe,larry,curly"
You shouldn't confuse arrays with lists.
This is a list: {...}. It has no length or other Array properties.
This is an array: [...]. You can use array functions, methods and so, like someone suggested here: someArray.toString();
someObj.toString(); will not work on any other object types, like lists.
Related
what is the best way to convert below array into a string and Name, value should be separated by : Json objects are separated by |.
let arr = [
{
"name":"abc",
"value":"21"
},
{
"name":"abcd",
"value":"212"
}
];
function arrToString(arr){
//logic
return "abc:21|abcd:212"
}
console.log(arrToString(ar));
Expected output: "abc:21|abcd:212"
I have used this logic but I don't like this. I need more efficient logic.
let arr = [{
"name": "abc",
"value": "21"
},
{
"name": "abcd",
"value": "212"
}
];
function setKey(arr) {
let temp = "";
arr.forEach((ele, index) => {
let name = ele.name;
let value = ele.value;
if (arr.length - 1 == index) {
temp = temp + name + ":" + value
} else {
temp = temp + name + ":" + value + "|";
}
});
console.log(temp);
}
setKey(arr);
function arrToString(arr){
let returnString = ''
arr.forEach((item, index) => {
if(index !== 0) returnString += '|'
returnString += `${item.name}:${item.value}`
})
return returnString
}
Hope this will solve your question
You can easily perform the conversion by exploiting the functional features of Javascript, in particular the map function:
function arrToString(arr){
return arr.map(x => x.name + ":" + x.value).join('|')
}
#danieleds'a answer with an arrow function :)
const arrToString = arr => arr.map(x => x.name + ":" + x.value).join('|')
You can use a combination of the map and join function like this:
function arrToString(arr) {
return arr.map(item => `${item.name}:${item.value}`).join("|")
}
In this case the map function, which is a higher-order function, applies a function for each item in the arr array. In this case, we create the desired string for each item. The join function combines all the strings (e.g. abc:21, abcd:212) together by separating the values with a pipe (|)
Here is one way with slice(which is used to remove characters from strings or elements from array):
function arrToString(arr){
let ans = "";
for(let i = 0 ; i < arr.length;i++){
ans += (arr[i].name + ":" + arr[i].value);
ans+= "|";
}
ans = ans.slice(0,-1);
return ans
}
In another simple way,
function objToStr(objArr){
let strArray = [];
objArr.forEach((item) => {
strArray.push(item.name+":"+item.value);
})
return strArray.join("|");
}
Suppose that I have the following dictionary:
var d = {
'foo': 0,
'bar': 1
};
How can I easily convert it to string like this?
foo=0&bar=1
Is there any built-in methods that can help me with it?
Not sure about built-in methods, but you can simply do
Object.keys( d ).map( function(key){ return key+"="+d[key] }).join("&") //outputs "foo=0&bar=1"
If you are using jQuery use $.param(data, true);
Or, For pure javascript you can use
function serialize(obj) {
var str = [];
for(var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
serialize(data);
var d = {
'foo': 0,
'bar': 1
};
var finalString = "";
for(var key in d){
finalString += key + "=" + d[key] + "&";
}
finalString = finalString.slice(0, -1);
console.log(finalString);
Use a reducer function:
var obj = {
'foo': 0,
'bar': 1
};
var str = Object.keys(obj).reduce(function(acc, key, index) {
return acc + (index === 0 ? '' : '&') + key + '=' + obj[key];
}, '');
console.log(str) // => 'foo=0&bar=1'
Check the working example.
You can achieve this with the reduce method (since you are "reducing" the values of the object to a single string.
A concise ES6 example might look like this:
Object.keys(d).reduce((a,b,i) => `${a}${i ? '&':''}${b}=${d[b]}`,'')
I have to redo the functionality of JSON.stringify for a class and I am stuck...
If I am passed an array, I need to return the exact array as a string. However, when I return the array, it strips the quotations off of any values that are strings. For example:
var arr = [8, "hello"];
var addQuotes = function(arr){
return ('[' + arr + ']');
}
addQuotes(arr);
//"[8, hello]"
However, I need it to return:
"[8, "hello"]"
How do I preserve the quotation marks on array values?
I propose this code :
var arr = [8, "hello"];
var arrString = arr.map(x => typeof x === 'string' ? "\"" + x + "\"" : x);
result = "\"[" + arrString.join(", ") + "]\""
console.log(result); // ) "[8, "hello"]"
I have an javascript array of string that looks like:
A = ['a', 'b', 'c'];
I want to convert it to (all string):
strA = '"a","b","c"'
How do I achieve this?
You can use join with "," as glue.
var strA = '"' + A.join('","') + '"';
join will only add the glue between the array elements. So, you've to add the quotes to start and end of it.
Try this
A = ['a', 'b', 'c'];
A.toString();
alert(A);
Do you mean something like this? This works in chrome.
function transformArray(ar) {
var s = ar.map(function (i) {
return "\"" + i + "\","; })
.reduce(function(acc, i) {
return acc + i;
});
return s.substring(0, s.length-1);
}
transformArray(["a", "b", "c"]);
You could try just concatenating the values in a simple for loop
something like this:
var array = ["1", "a", 'b'];
var str = '';
for (var i = 0; i<array.length; i++){
str += '"' + array[i] + '",';
}
str = str.substring(0, str.length - 1);
or if you're feeling crazy you could do :
str = JSON.stringify(array)
str = str.substring(1, str.length -1);
I have a dynamically generated Array:
myArr = ["val0a", "val1a", "val2a"... "val600a"]
I am having problems appending a new array values to this array in a loop. My Array should look like this after the append:
myArr = ["val0a", "val1a val1b", "val2a val2b"... "val600a"]
Please note that the new array and the old one do not have the same length.
How can I do this? It have to be something simple but I can't figure it out.
You can write a function along the lines of this:
Array.prototype.appendStringToElementAtIndex = function(index, str) {
if(typeof this[index] === 'undefined' || typeof this[index] !== 'string') return false;
this[index] += ' ' + str;
};
myArr = ["val0a", "val1a", "val2a"];
myArr.appendStringToElementAtIndex(1, "val1b");
console.log(myArr.join(', ')); //val0a, val1a val1b, val2a
myArr.push(myArr[myArr.length - 1].split(" ").push("val42").join(" ")); // even
to append a value to an element of an array you can just do this:
myArr = ["val0a", "val1a", "val2a"... "val600a"];
indexToAppendTo = 2;
val2 = "val2b"
myArr[ indexToAppendTo ] += (" " + val2) ;
To concatenate to an element that's a string:
myArr[2] = myArr[2] += 'blah';
To reassign it:
myArr[2] = 'foo';