this is how my object looks like:
, but I need just one object like
obj = {
var: "DB3,B0",
zahl: "DB3,Int2",
zahl2: "DB3,Int4",
...
...
};
How do I convert it?
I tried different things but it all won't work inside a for loop.
I generate my Object from a string with a code like this:
var text = msg.payload;
var nt = text.split(" ");
var n = nt.length;
var add = [];
var name = [];
var ab = [];
var variables = {};
for (var i = 0; i < n; i++) {
ab[i] = nt[i].split(";");
add[i] = ab[i][0];
name[i] = ab[i][1];
variables[i] = {[name[i]] : add[i]};
}
msg.payloadvars = variables;
return msg;
I think it should be quite simple but I don't come to any solution.
input looks like
DB3,B0;var DB3,Int2;zahl DB3,Int4;zahl2 DB3,Int6;zahl3 DB3,Int8;zahl4
DB3,Int10;zahl5 .....
You could split the string by groups and then for value and key.
var string = 'DB3,B0;var DB3,Int2;zahl DB3,Int4;zahl2 DB3,Int6;zahl3 DB3,Int8;zahl4 DB3,Int10;zahl5',
target = Object.assign(
...string.split(' ').map(s => (([v, k]) => ({ [k]: v }))(s.split(';')))
);
console.log(target);
Use Array.reduce
let str = "DB3,B0;var DB3,Int2;zahl DB3,Int4;zahl2 DB3,Int6;zahl3 DB3,Int8;zahl4 DB3,Int10;zahl5";
let obj = str.split(" ").reduce((a,c) => {
let v = c.split(";");
Object.assign(a, {[v[1]]: v[0]});
return a;
}, {});
console.log(obj);
if you want to make single object then you should try this:
var variables = {};
for (var i = 0; i < n; i++) {
ab[i] = nt[i].split(";");
add[i] = ab[i][0];
name[i] = ab[i][1];
variables[name[i]] = add[i];
}
console.log(variables);
Related
Take the following string:
/foo/1/bar/2/cat/bob
I need to parse this into an object or array which ends up being:
foo = 1
bar = 2
cat = bob
var sample = "/foo/1/bar/2/cat/bob".substring(1);
var finalObj = {};
var arr = sample.split('/');
for(var i=0;i<arr.length;i=i+2){
finalObj[arr[i]] = arr[i+1];
}
console.log(finalObj);
const str = '/foo/1/bar/2/cat/bob/test/'
const parts = str.split('/')
.filter(val => val !== '')
const obj = {}
for (let ii = 0; ii < parts.length; ii+=2) {
const key = parts[ii]
const value = parts[ii+1]
obj[key] = !isNaN(value) ? Number(value) : value
}
console.log(obj)
Regular expressions is the tool of choice for all kinds of parsing:
str = '/foo/1/bar/2/cat/bob'
obj = {};
str.replace(/(\w+)\/(\w+)/g, (...m) => obj[m[1]] = m[2]);
console.log(obj);
Just for the fun of it,
let str = "/foo/1/bar/2/cat/bob",
arr = str.split("/"),
obj = {};
arr.shift();
while (arr.length) obj[arr.shift()] = arr.shift();
I have two json:
I want to create json with those two array;
var __columns = ["Field1", "Field2", "Field3", "Field4"];
var __rows = ["valueField1_1", "valueField2_1", "valueField3_1", "valueField4_1", "valueField1_2", "valueField2_2", "valueField3_2", "valueField4_2", "valueField1_3", "valueField2_3", "valueField3_3", "valueField4_3"];
The thing is that I wanna create something like this
var json = [{
"Field1":"valueField1_1",
"Field2":"valueField2_1",
"Field3":"valueField3_1",
"Field4":"valueField4_1"
},{
"Field1":"valueField1_2",
"Field2":"valueField2_2",
"Field3":"valueField3_2",
"Field4":"valueField4_2"
},{
"Field1":"valueField1_3",
"Field2":"valueField2_3",
"Field3":"valueField3_3",
"Field4":"valueField4_3"
}]
ES6 solution using Array.from and Array#reduce methods.
var __columns = ["Field1", "Field2", "Field3", "Field4"];
var __rows = ["valueField1_1", "valueField2_1", "valueField3_1", "valueField4_1", "valueField1_2", "valueField2_2", "valueField3_2", "valueField4_2", "valueField1_3", "valueField2_3", "valueField3_3", "valueField4_3"];
var res = Array.from({
// generate array with particular size
length: __rows.length / __columns.length
// use map function to generate array element
}, (_, i) => __columns.reduce((obj, e, i1) => {
// define object property based on the index values
obj[e] = __rows[i * __columns.length + i1];
return obj;
// set empty object as initial argument
}, {}));
console.log(res);
function convertToJsonArr(__columns, __rows){
var obj = {};
var arr = [];
var len = __columns.length;
var count = 0;
$.each(__rows , function(key, value){
if(count >= len){
count = 0;
arr.push(obj);
obj = {};
}
obj[__columns[count++]] = value;
})
arr.push(obj);
return arr;
}
you can call like convertToJsonArr(__columns, __rows);
One way to achieve this is using loops
var __columns = ["Field1", "Field2", "Field3", "Field4"];
var __rows = ["valueField1_1", "valueField2_1", "valueField3_1", "valueField4_1", "valueField1_2", "valueField2_2", "valueField3_2", "valueField4_2", "valueField1_3", "valueField2_3", "valueField3_3", "valueField4_3"];
var arr = [];
for(var i = 0; i < __rows.length; i = i + __columns.length){
var tempObj = {};
for(var j = 0; j < __columns.length; ++j){
tempObj[__columns[j]] = __rows[i];
}
arr.push(tempObj);
}
console.log(arr);
How to count the JSON object and on the basis of count take the same output
var obj =
[
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
];
First I would like the count after it on the basis of count. I want same output like input.
for Count:-
var count = 0;
function getCount() {
for (var i = 0; i < obj.length; i++) {
count++;
}
return count;
}
for output :-
function showDetails() this is not giving the proper output
{
for(var j=0; j< count; j++){
obj.push([{j}]);
}
alert(obj.name);
}
alert(showDetails());
And I want an output like:-
var obj =
[
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
];
Can anybody help me please?
var data ="January,February,March,April,May,June,July,August,September,October";
var obj = data.split(',').map((item)=>{
return {
name:item
}
});
obj will be the desired output
var str = "January,February,March,April,May,June,July,August,September,October";
var arr = str.split(',').map(function(v) {
return {name: v};
});
console.log(arr);
var str = "January,February,March,April,May,June,July,August,September,October";
var months = str.split(",");
var result = [];
for (i in months)
{
var month = {};
month.name = months[i];
//you can do more things else here, for example:
//month.monthOfYear = (i+1);
//month.numberOfDay = 123123123;
result.push(month);
}
You can do something like this:
var array = string.split(",");
var finalArray = [];
array.forEach(function(item){
var obj = {
name: item
}
finalArray.push(obj);
});
console.log(finalArray);
MDN reference
use var array = string.split(',');
For a more ES2015 heavy version. Constants, arrow function and implicit return statement.
const str = 'January,February,March,April,May,June,July,August,September,October'
const result = str.split(',').map(name => ({name}))
console.log(result)
Let's say I have an object like this one
{0:"first",2:"second",5:"first"};
I want to create a new object like this one:
{'first':{0:{value1:0,value2:0},5:{value1:0,value2:0}},'second':{2:{value1:0,value2:0}}}
How can I achieve this.
you can try this code (i dont test it).
thenew is the output, and theold is the input.
var thenew = {};
for(var k in theold) {
var v = theold[k];
if(!thenew[v]) {
thenew[v] = {};
}
thenew[v][k] = '';
}
Using Lodash:
var transformedObject = _.transform(yourObject,
function(r, v, k){
if(!r[v]){r[v] = {}}; r[v][k] = {};
})
I have tag like this, how the best way to get every key and value of those attribute and populate it within an array (number of attribute will be increasing)?
myData = '[data attr1="value1" attr2="value2" attr3="value3"]';
and get result array :
var arr = new Array();
arr['attr1'] = "value1";
arr['attr2'] = "value2";
arr['attr3'] = "value3";
and so on...
This probably does what you want, though it assumes that tag is already in the format you have described, i.e. a singular occurrence of [data ... ].
Also, the regular expression is purely based on what I've seen in your question; not sure whether it will break on other strings.
function decode(tag)
{
var r = /(\w+)="([^"]*)"/g,
h = {};
while ((m = r.exec(tag)) !== null) {
h[m[1]] = m[2];
}
return h;
}
Since you have string key in the data, use jquery object instead of array.
var arr = {};
var str = '[data attr1="value1" attr2="value2" attr3="value3"]';
var n = str.split('[data ');
var str_arr = n[1].replace(']','').split(" ");
jQuery.each(str_arr,function(val){
var x = str_arr[val].split('=');
arr[x[0]] = x[1].replace('"','').slice(0,-1);
});
console.log(arr);
Try this code. It may help you.
Here is the DEMO
Though it can be more optimized if you put some more details about your code.
var tagRe = /\[(\w+)((?:\s+\w+="[^"]{0,50}")*)\s*]/g;
var attrRe = /\b(\w+)="([^"]*)"/g;
function parse(text) {
var result = [];
tagRe.lastIndex = 0; // reset start position
var tagMatch = tagRe.exec(text);
while (tagMatch) {
var currentTag = { 'name': tagMatch[1], 'attrs': {} };
var attrString = tagMatch[2];
attrRe.lastIndex = 0;
var attrMatch = attrRe.exec(attrString);
while (attrMatch) {
var attrName = attrMatch[1];
var attrValue = attrMatch[2];
currentTag.attrs[attrName] = attrValue;
attrMatch = attrRe.exec(attrString); // next match
}
result.push(currentTag);
tagMatch = tagRe.exec(text);
}
return result;
}
parse('[data attr1="value1" attr2="value2" attr3="value3"]');
> [{name:'data',attrs:{attr1:'value1',attr2:'value2',attr3:'value3'}}]
This works for any number of tags in the string. The name of the tag does not matter.