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] = {};
})
Related
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);
I don't know what must be title for my question, I think it's so complicated. So, I have A array:
["87080207", "87101133", "91140156"]
And B Array:
["97150575", "97150575", "90141063"]
This B array, I put on html select value. Each of them(A and B array) is related. I need to show 87080207,87101133 (A array) when I choose value 97150575 (B array).
I have tried, but it didn't work.This is my code:
var a=[];
var b=[];
var arrayLength = dataComponentValuation.length;
for (var i = 0; i < arrayLength; i++) {
a.push(dataComponentValuation[i].valuated);
b.push(dataComponentValuation[i].valuator);
}
var ajoin = a.join();
var bjoin = b.join();
$('#valuatedEmpCompId_before').val(ajoin);
$('#valuator_before').val(bjoin);
In select, I put a function, this is it:
function emptyValuated() {
var valby = $("#valBy").val(); //chosen value from select
var b_valby = $("#valuator_before").val();
var b_valuated = $("#valuatedEmpCompId_before").val();
if(b_valby != ''){
if(valby != b_valby)
{
$("#valuatedEmpCompId").val('');
}
else{
$("#valuatedEmpCompId").val(b_valuated);
}
}
else{
$("#valuator_before").val(valby);
$("#valuatedEmpCompId").val(b_valuated);
}
}
Help me please...
As suggested, you could use an object as reference to the values of array A.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
object = Object.create(null);
arrayB.forEach(function (b, i) {
object[b] = object[b] || [];
object[b].push(arrayA[i]);
});
console.log(object);
I guess nowadays the Map object is a perfect solution for these jobs.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
myMap = arrayB.reduce((p,c,i) => p.has(c) ? p.set(c, p.get(c).concat(arrayA[i]))
: p.set(c,[arrayA[i]])
, new Map());
console.log(myMap.get("97150575"));
console.log(myMap.get("90141063"));
I am using javascript in my app which is a rhino javascript engine. I like to use array for an array.
The following code is my actual working code.
while (input.hasNext()) {
var data = input.next();
var new_data = {};
var i = 0;
while(i<data.get('total_entries')){
new_data.entries = data.get('total_entries');
new_data.id = data.get('out').get(i).get('id');
output.write(new_data);
i++;
}
}
I need to create array for new_data[].
while (input.hasNext()) {
var data = input.next();
var new_data[] = {};
var i = 0;
while(i<data.get('total_entries')){
new_data[i].entries = data.get('total_entries');
new_data[i].id = data.get('out').get(i).get('id');
output.write(new_data[i]);
i++;
}
}
But its not working. So, help me to create array variable in it.
Thanks.
You mean something like this:
while (input.hasNext()) {
var data = input.next();
var new_data = [];
var i = 0;
while(i<data.get('total_entries')){
new_data.push({entries: data.get('total_entries'), id: data.get('out').get(i).get('id')});
output.write(new_data[i]);
i++;
}
}
var new_data[] = {};
First of all, that's invalid JavaScript.
new_data[i]
Looks like you want new_data to be an array of objects. Why not declare it as one and add objects on every iteration of the while loop:
var new_data = [];
while(...){
new_data.push({
entries: ...
id: ...
});
}
I have two JavaScript arrays below that both have the same number of entries, but that number can vary.
[{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}]
[{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}]
I want to combine these two arrays so that I get
[{"5006":"GrooveToyota"},{"5007":"GrooveSubaru"},{"5008":"GrooveFord"}]
I'm not sure how to put it into words but hopefully someone understands. I would like to do this with two arrays of arbitrary length (both the same length though).
Any tips appreciated.
It's kind of a zip:
function zip(a, b) {
var len = Math.min(a.length, b.length),
zipped = [],
i, obj;
for (i = 0; i < len; i++) {
obj= {};
obj[a[i].branchids] = b[i].branchnames;
zipped.push(obj);
}
return zipped;
}
Example (uses console.log ie users)
var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var combined = [];
for (var i = 0; i < ids.length; i++) {
var combinedObject = {};
combinedObject[ids[i].branchids] = names[i].branchnames;
combined.push(combinedObject);
}
combined; // [{"5006":"GrooveToyota"},{"5006":"GrooveSubaru"},{"5006":"GrooveFord"}]
Personally, I would do it IAbstractDownvoteFactor's way (+1), but for another option, I present the following for your coding pleasure:
var a = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var b = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var zipped = a.map(function(o,i){ var n={};n[o.branchids]=b[i].branchnames;return n;});
similar to #robert solution but using Array.prototype.map
var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}],
names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}],
merged = ids.map(function (o, i) { var obj = {}; obj[o.branchids]=names[i].branchnames; return obj; });
merged; //[{5006: "GrooveToyota"}, {5006: "GrooveSubaru"}, {5006:"GrooveFord"}]
Cheers!
I am trying to have a javascript object tree behave like a php associative array in the following way.
var key1 = 'a';
var key2 = 'b';
var key3 = 'c';
var obj[key1][key2][key3] = 'd';
However, in javascript I believe you need to define each property/object pair individually, forming deeper leaves. Something like:
var obj[key1] = {};
var obj[key1][key2] = {};
...
Is there a way to simplify or shorten this script?
Thanks
I don't know if there's a "natural" way to do it, but you could do it like this:
function phpLike(){};
phpLike.prototype.set = function ()
{
var l = arguments.length;
if (l<2) return;
var o = this;
for (var i=0; i<l-2; i++)
{
if (o[arguments[i]] === undefined) o[arguments[i]] = {};
o = o[arguments[i]];
}
o[arguments[l-2]] = arguments[l-1];
}
// Test
var key1 = 'a';
var key2 = 'b';
var key3 = 'c';
var obj = new phpLike();
obj.set(key1, key2, key3, 'd');
alert(obj[key1][key2][key3]);
function setPropertyByKeyPath(obj, path, val) {
var key;
while (path.length > 1) {
key = path.shift();
obj[key] = typeof obj[key] === "object" ? obj[key] : {};
obj = obj[key];
}
obj[path.shift()] = val;
}
var o = {};
setPropertyByKeyPath(o, ['foo', 'bar'], 5);
alert(o.foo.bar)
Not directly, as far as I know, but how about using a little helper function?
function kv1(k, v) {
var o = { };
o[k] = v;
return o;
}
var obj = kv1(key1, kv1(key2, kv1(key3, 'd')));
I just thought of an answer inspired by Will's post: Construct a json string and then eval().
var obj = eval("{" + key1 + ": {... }};");
This kind of fulfils my search for a more concise way of declaring an object tree and deep leaf. But, it is ugly, confusing and I would avoid it like the plague.
var obj = { key1: { key2: { key3: 'd' } } }
This syntax is the basis of the format known as JSON: http://en.wikipedia.org/wiki/JSON