0

I want to do the following:

// an object
var object = {
    one: null,
    two: null,
    three: null
};

// an array
var array = ['this is one', 'this is two', 'this is three'];

I now want to merge them both together so I get;

var merged = {
    one: 'this is one',
    two: 'this is two',
    three: 'this is three'
};

I don't want to use any 3rd library just pure javascript (ECMA5).

So what is the trick?

Regards, bodo

6
  • 3
    Your question is extremely unclear, please try to explain what it is you want to do exactly. Commented Sep 14, 2012 at 12:28
  • Do you want to see all properties when printed ? What command do you use for printing ? Commented Sep 14, 2012 at 12:29
  • +1 to @Jeroen. What do you mean by "parallel"? Commented Sep 14, 2012 at 12:32
  • Can you tell us what arguments is ? Commented Sep 14, 2012 at 12:37
  • 3
    By definition, the order of keys in an object is undefined, so this will be hacky in at least some way or the other. Any other approach on sourcing your pairs? Commented Sep 14, 2012 at 12:51

1 Answer 1

2

Try this:

// an object 
var object = {
    one: null,
    two: null,
    three: null
};

// an array 
var array = ['this is one', 'this is two', 'this is three'];

function merge(arraysrc, array2dest) {

    var x, i = 0;

    var merged = [];

    for (x in array2dest) {
        var obj = {};
        obj[x] = arraysrc[i++];
        merged.push(obj);
    }
    return merged;
}

var a = merge(array, object);

alert(JSON.stringify(a));​

http://jsfiddle.net/6mQYN/

Sign up to request clarification or add additional context in comments.

2 Comments

Results might be unpredictable, object key order is not defined.
this is only a example how he can do this. Order, length have to be handled

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.