How to Convert key/value pair String to a JSON object? - javascript

How can I covert key=value pair string to json object
input :
test = one
testTwo = two
Output should be json object
"test":"one","testTwo":"two"

Is input a string? You could first split it by \n to get an array of key/value-pairs, and then split each pair by =, to get an array of the key and the value.
var input = `test = one
testTwo = two
testThree = three
testFour = four`;
var output = input.split('\n').reduce(function(o,pair) {
pair = pair.split(' = ');
return o[pair[0]] = pair[1], o;
}, {});
console.log(output);

The safest way to do it is JSON.parse(string)

Related

Javascript array - split

I have a text file in which I have data on every line. It looks like this:
number0;text0
number1;text1
number2;text2
..and so on
So I loaded that text file into a variable via xmlhttprequest and then I converted it into an array using split by "\n" so now the result of lineArray[0] is number0;text0.. And now what I need is to split that array again so I could use number0 and text0 separately.
My idea being that I want to get the text0 by searching number0 for example lineArray[i][1] gives me texti..
Any ideas how to proceed now?
Thanks
You need to do an additional split on ; as split(';') so that lineArray[0][1], lineArray[1][1] and so on gives you text0, text1 and so on.
var str = `number0;text0
number1;text1
number2;text2`;
var lineArray = str.split('\n').map(function(item){
return item.split(';');
});
console.log(lineArray);
console.log(lineArray[0][1]);
console.log(lineArray[1][1]);
Knowing I'm late, still making a contribution.
As everyone else said, split it again.
let text = "number0;text0\nnumber1;text1\nnumber2;text2"
let data = text.split('\n');
var objects = {};
for (var i = 0; i < data.length; i++) {
let key = data[i].split(';')[0]; // Left hand value [Key]
let value = data[i].split(';')[1]; // Right hand value [Value]
// Add key and value to object
objects[key] = value;
}
// Access by property
console.log(objects);
Using forEach
let text = "number0;text0\nnumber1;text1\nnumber2;text2"
let data = text.split('\n');
var objects = {};
data.forEach((elem) => {
let key = elem.split(';')[0]; // Left hand value [Key]
let value = elem.split(';')[1]; // Right hand value [Value]
objects[key] = value;
});
// Access by property
console.log(objects);
Just use split again with ";", like that:
myVar = text.split(';');
like #Teemu, #Weedoze and #Alex said
Convert the array into an object
Make an object out of it with another String split. To do so you can use the .reduce method to convert the array of strings into an object.
const strings = ['number0;text0', 'number1;text1', 'number3;text3', 'number4;text4'] ;
const obj = strings.reduce((acc,curr) => {
const [key, value] = curr.split(';');
acc[key] = value;
return acc;
}, {});
console.log(obj)
This way you can access text4 buy calling obj['number4'].
More about .reduce
The reduce method works by looping through strings
on each step acc is the accumulator: it contains the object that is getting filled with key/value pairs.
cur is the current item in the step
const [key, value] = curr.split(';') will to split the string into two strings and assign each to a seperate variable: key and value. It's called destructuring assignment
then I assign the key/value pair to the accumulator
the .reducemethod will return the accumulator on his state on the last step of the loop
Something like this could do the trick:
let a = "number0;text0\nnumber1;text1\nnumber2;text2";
let lines = a.split('\n');
let vals = [];
for(let line of lines) {
vals.push(line.split(';'))
}
console.log(vals); // Output
The last four lines create an empty array and split on the ';' and append that value to the vals array. I assume you already have the something like the first 2 lines

save and display an array of JSON/JS object(name/value pair) value as a comma separated string

var obj = {
aray1:[1,2],
aray2:["a","b"],
aray3:["ab","abab"]
};
this is the object i have values and i want to store the above array values as as a comma separated string and display as comma separated string on UI.
DB used is Mongo.
I think you are looking for a join method on arrays.
What you can do is obj.aray1.join(",") which will return 1,2 that you can display in your UI
As #eddyP23 mentioned, [].join will do the job for you.
var obj = {
aray1:[1,2],
aray2:["a","b"],
aray3:["ab","abab"]
};
var result = "";
for(key in obj){
result += ","+obj[key].join(",")
}
console.log(result.substring(1));
var obj = {
aray1:[1,2],
aray2:["a","b"],
aray3:["ab","abab"]
};
var a = Object.keys(obj).map(function(key){
return obj[key]
})
console.log(a.toString())

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)

Convert string into array of object in 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).

Using JavaScript's split to chop up a string and put it in two arrays

I can use JavaScript's split to put a comma-separated list of items in an array:
var mystring = "a,b,c,d,e";
var myarray = mystring.split(",");
What I have in mind is a little more complicated. I have this dictionary-esque string:
myvalue=0;othervalue=1;anothervalue=0;
How do I split this so that the keys end up in one array and the values end up in another array?
Something like this:
var str = "myvalue=0;othervalue=1;anothervalue=0;"
var keys = [], values = [];
str.replace(/([^=;]+)=([^;]*)/g, function (str, key, value) {
keys.push(key);
values.push(value);
});
// keys contains ["myvalue", "othervalue", "anothervalue"]
// values contains ["0", "1", "0"]
Give a look to this article:
Search and Don't Replace
I'd still use string split, then write a method that takes in a string of the form "variable=value" and splits that on '=', returning a Map with the pair.
Split twice. First split on ';' to get an array of key value pairs. Then you could use split again on '=' for each of the key value pairs to get the key and the value separately.
You just need to split by ';' and loop through and split by '='.
var keys = new Array();
var values = new Array();
var str = 'myvalue=0;othervalue=1;anothervalue=0;';
var items = str.split(';');
for(var i=0;i<items.length;i++){
var spl = items[i].split('=');
keys.push(spl[0]);
values.push(spl[1]);
}
You need to account for that trailing ';' though at the end of the string. You will have an empty item at the end of that first array every time.

Categories

Resources