Convert string into array of object in javascript - javascript

Need to convert string into array of object in JavaScript. Here is the example,
var str = "1,2";
output:
"values":[
{"id":"1"},
{"id":"2"}
];

Make use of map():
var str = "1,2";
var s = str.split(',').map(function(x){
return {"id" : x};
})
str = {"values" : s};
console.log(JSON.stringify(str));

try this:
var str = "1,2";
str = str.split(",");
var obj = {'value':[]};
str.forEach(function(val){
obj.value.push({'id':val})
});

str = "1,2"
var res = str.split(",");
values = []
for each (var item in res ) {
values .push({
id: item
});
}
console.log(JSON.stringify(values));
use split , list push and loop

Use map. Both split (for converting the string to an array) and map (which returns a new array for each element of the array that is passed through the provided function) are chainable so you can do the following:
var values = str.split(',').map(function (el) {
return { id: el };
});
DEMO
It's not clear whether you want just an array of objects, or a JSON string of that array. If it's the latter, use JSON.stringify(result).

Related

Convert an string to object with duplicate keys to an array

I have a string that needs to be converted to an object. But the string has the duplicated items. Since JSON Objects cannot contain 2 items with the same key. The second item is overwriting the first item.
How to merge the duplicate items and push to an array?
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
var stringMod = string.split("&");
var stringObj = {};
stringMod.forEach(function(json) {
var jsonSplit = json.split("=");
stringObj[jsonSplit[0]] = [jsonSplit[1]];
});
console.log(stringObj,'stringObj');
Desired output:
{
"test-1": ["owner","driver"],
"test-2": ["Yes"],
"test-3": ["2"],
"test-4": ["sun","moon"],
"test-5": ["not-agree"],
"test-6": ["dogs","testing+js+object"],
"test-7": ["Testing+js+function","Testing+js+array"]
}
Here is the link to working fiddle: https://jsfiddle.net/sjoh9rqp/
Can you help me how to accomplish this ?
You can use a URLSearchParams to accomplish this, since it treats the string as url parameters it does do decoding though.
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
var data = new URLSearchParams(string);
var obj = {};
for (let x of data.keys()){
obj[x] = data.getAll(x);
}
console.log(obj);
Using URLSearchParams to parse the query string helps simplify this
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
const params = new URLSearchParams(string),
res = {};
params.forEach((v,k)=> {
res[k] = res[k] || []
res[k].push(v);
})
console.log(res)
For variety, here's the answer solved with reduce(), though I have to admit URLSearchParams is more elegant
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
let obj = string.split('&').reduce((b,a) => {
let t = a.split('=');
if (b.hasOwnProperty(t[0])) b[t[0]].push(t[1]);
else b[t[0]] =[t[1]];
return b;
},{});
console.log(obj)

Concatenate array into string

I have this:
var myarray = [];
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
And I want to get the string:
"first":"$firstelement","second": "$secondelement"
How can I do it?
What you have is invalid (even if it works), arrays don't have named keys, but numeric indexes.
You should be using an object instead, and if you want a string, you can stringify it as JSON
var myobject = {};
myobject["first"] = "$firstelement";
myobject["second"] = "$secondelement";
var str = JSON.stringify(myobject);
console.log(str)
First of all, you'd want to use an object instead of an array:
var myarray = {}; // not []
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
The easiest way, then, to achieve what you want is to use JSON:
var jsonString = JSON.stringify(myarray);
var arrayString = jsonString.slice(1, -1);
JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
var myarray = {};
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
console.log(JSON.stringify(myarray));
Use JSON.strinify()
JSON.stringify(item)

How to check if a string contains all the elements of an array in Javascript

I have a string apple_mango_banana and an array containing [apple,mango].
I want to check if my string contains all of the elements present in the array, if so, I want to show a div with the same ID as my string.
Use every() function on the arr and includes() on the str;
Every will return true if the passed function is true for all it's items.
var str = 'apple_mango_banana';
var arr = ['apple','banana'];
var isEvery = arr.every(item => str.includes(item));
console.log(isEvery);
You should use Array.every for such cases.
var s = "apple_mango_banana";
var s1 = "apple_mago_banana";
var fruits = ["apple","mango"];
var allAvailable = fruits.every(function(fruit){
return s.indexOf(fruit)>-1
});
var allAvailable1 = fruits.every(function(fruit){
return s1.indexOf(fruit)>-1
});
console.log(allAvailable)
console.log(allAvailable1)
var string="ax_b_c_d";
var array=['b','c','ax','d'];
var arr=string.split("_");
if(array.sort().join("")==arr.sort().join("") && arr.length==array.length)
{
console.log("match");
}

Manipulate Json String Jquery

Supposed that I have this JSON STRING that is stored in a vairable:
{"name":"Joene Floresca"},{"name":"Argel "}
How can I make it
["Joene", "Argel"]
You mention you have a string. Use JSON.parse for that. Also, make sure it is an array. Afterwards, you can manually iterate through each object in the array and push the value
var str = '[{"name": "Joene Floresca"},{ "name": "Argel "}]';
var objA = JSON.parse(str);
var values = [];
for (var i = 0; i < objA.length; i++) {
for (var key in objA[i]) {
values.push(objA[i][key]);
}
}
console.log(values);
Assuming your JSON is an array, you can use map:
// Your JSON string variable
var jsonString = '[{"name":"Joene Floresca"},{"name":"Argel "}]';
// Parse the JSON to a JS Object
var jsObject = $.parseJSON(jsonString);
// Use map to iterate the array
var arr = $.map(jsObject, function(element) {
// Return the name element from each object
return element.name;
});
console.log(arr); // Prints ["Joene Floresca", "Argel "]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can iterate over objects inside array and store the names in a second array.
var data = JSON.parse('[{"name":"Joene Floresca"},{"name":"Argel "}]');
var names = [];
data.forEach(function(model) {
names.push(model.name);
});
// names now contains ["Joene Floresca", "Argel"]
alert(names);

How to convert a array containing object string to regular key object pair?

I am trying to convert my uri to object value, as a success level i converted and splited in to array values with colon. But i am not able to onvert those to regular object. any one suggest me a good way. I am suing underscorejs with me.
here is my code :
var ar = ["id:1231", "currency:GBP"];
var outPut = _.map(ar, function(item){
return '{' + item + '}';
})
console.log(outPut); //consoles as ["{id:1231}", "{currency:GBP}"]
how can i get result like this:
var object = {id:1231, currency:GBP}
is underscore has any in build method for this?
There are several ways you could go about this, and Underscore offers helpers for them.
One way would be to use _.reduce to incrementally add key/value pairs to an initially empty "result" object:
var obj = _.reduce(ar, function(result, item) {
var keyAndValue = item.split(":");
result[keyAndValue[0]] = keyAndValue[1];
return result;
}, {});
Note that you can do the same without Underscore unless you have to support IE 8 or earlier.
Without any third part library:
var output = {} ;
var ar = ["id:1231", "currency:GBP"];
ar.forEach(function (item) {
var values = item.split(':') ;
output[values[0]] = values[1] ;
}) ;
Output console.log(output):
Object {id: "1231", currency: "GBP"}
Here is another version using jQuery:
var newObj = {};
$.each( ar, function( i, v ) {
var kv = v.split( ":" );
newObj[ kv[0] ] = kv[ 1 ];
});
// newObj = {id:"1231", currency:"GBP"}

Categories

Resources