0

I have 3 different arrays, one with column names of a table and the other with data. How can I combine them to form one single json object in AngularJS?

var keyArray = ["Col1","Col2","Col3",...];
var ValArray1 = ["v1.1","v1.2","v1.3",...];
var ValArray2 = ["v2.1","v2.2","v2.3",...];

I want a json something like this

entries[
{
name: "Col1",
value: "v1.1" 
},
{name: "Col2",
value: "v1.2" 
},
...,
{name: "Col3",
value: "v2.3" 
}
]
6
  • 1
    it is not completely clear how you need to mix the keyArray with the two ValArrays.. you want just one object, first with the objects from, combination of keyArray with ValArray1 and then the objects from combination of keyArray with ValArray2 ? Commented Oct 29, 2015 at 19:58
  • Yes. The first array contains the column names of a table and the other contain data. Commented Oct 29, 2015 at 20:02
  • but this could be merely a javascript question, you don't need angularjs at all. Commented Oct 29, 2015 at 20:04
  • sorry my bad. I want it like this Commented Oct 29, 2015 at 20:05
  • { Col1:"v1.1" }, { Col2:"v1.2" }, ..., { Col3:"v2.3" } Commented Oct 29, 2015 at 20:07

2 Answers 2

0

is this ok for you ? You don't need angularjs at all.

var addToArray = function(entries, keys, values){
    for(var i = 0; i < keys.length; i++){
        if(keys[i] && values[i]) {
            var obj = {};
            obj[keys[i]] =   values[i];            
            entries.push(obj);
        }
    }
}

var entries = [];
addToArray(entries, keyArray, ValArray1);
addToArray(entries, keyArray, ValArray2);

if you want to use something from angular, you could use angular.forEach instead

This will mix keys with array one, and then keys with array two.. I did it in that way because in your question is not clearly stated when it should stop using array one and start using array two (after you use all the values in array two, maybe ?)

anyway, for your purpose I think the key point is

obj[keys[i]] =   values[i];   

This will let you create a property name with the string in your array

0
0

How about entries = { "Col1" : "v1.1", "Col2" : "v1.2", "Col3" : "v2.3" } So you can access it as entries[Col1] which is v1.1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.