2

I am looking for a solution, to push/convert array items into a object back, without using keys?

function pleaseBuy(){
    var args = arguments;
    for(var i = 0; i < arguments[0].length; ++i) {
        args += args[i];
    };
};

function getList(){
   return ["pepsi","cola","7up"];
}

var list = ({ favorite: "drpepper"}, getList())
pleaseBuy(list)

Expected result:

args = ({ favorite: "drpepper"}, "pepsi", "cola", "7up")

5 Answers 5

2

No need for the pleaseBuy function, I'd say:

function getList(){
   return ["pepsi","cola","7up"];
}

var list = getList().concat( { favorite: "drpepper" } );
//                                     ^ NB should be :
// or favorite first
var list = [{ favorite: "drpepper" }].concat(getList());
/* 
   list now contains:
   ['pepsi, 'cola','7up',{ favorite: "drpepper" }]
*/

An object allways contains key-value pairs. If you want to convert an array to an object, you'll thus have to assign keys and values. For example:

var arr = [1,2,3,4,'some'], arr2Obj = {};
for (var i=0;i<arr.length;i=i+1){
   arr2Obj[arr[i]] = i;
}

/* 
   arr2Obj now contains:
   { 
     1: 0,
     2: 1,
     3: 2,
     4: 3,
     some: 4
   }
*/

Other example:

var arr = [1,2,3,4,'some'], arr2Numbers = {};
for (var i=0;i<arr.length;i=i+1){
       arr2Numbers[arr[i]] = !isNaN(Number(arr[i]));
}
/* 
   arr2Numbers now contains:
   { 
     1: true,
     2: true,
     3: true,
     4: true,
     some: false
   }
*/
Sign up to request clarification or add additional context in comments.

Comments

1

Do you mean the javascript push function?

Comments

1

Use .unshift() docs to prepend to an array.

var list = getList();
list.unshift( { favorite="drpepper"});

// [{ favorite="drpepper"}, "pepsi", "cola", "7up"]

Demo at http://jsfiddle.net/Ds9y5/

Comments

0

Try this:

var array = ["pepsi","cola","7up"];
array.push({ favorite: "drpepper"});

Or

var array2 = ["pepsi","cola","7up"];
var array = [{favorite: "drpepper"}];
for(var ctr = 0 ; ctr < array2.length ; ctr++){
  array.push(array2[ctr]);
}

Comments

0
var s = getList();
s.unshift({ favorite : "drpepper"}); // at the first place in array
s.push({ favorite : "drpepper"}); // at the last place in array
alert(s);

JavaScript push() Method
JavaScript unshift() Method

Comments

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.