0

I want to do something like this:

const foo = ['aba', 'bab'];
const bar = [1, 2];

and then create this array:

result = [
{
  text: foo[0]
  number: bar[0]
},
{
  text: foo[1]
  number: bar[1]
}
]  

Foo and bar will have equal lengths.

1
  • Will foo and bar always be the same length? Commented Dec 29, 2017 at 11:41

5 Answers 5

3

If your arrays have same length, you can use Array#map to iterate over each item, get the item and the index and then create the new array of objects setting the text to item and the number to bar[index].

const foo = ['aba', 'bab'];
const bar = [1, 2];

const mapped = foo.map((item, index) => ({text: item, number: bar[index]}));

console.log(mapped);

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

Comments

1

I would simply map one of the array and use the second parameters of the mapping function, the index, to get the value for the other one:

var result = foo.map((value, index) => ({
     text: value, number: bar[index],
}));

Comments

0

Simple solutin

let result = [] ;
const foo = ['aba','bab']
const bar = [1,2]
for(let i = 0 ; i<foo.length;i++){
  result[i]={}
  result[i].text = foo[i] ; 
  result[i].number = bar[i];
}
console.log(result) ;

Comments

0

Assuming the are always the same length, you can do:

var foo = ['aba','bab']
var bar = [1,2]

function makeObjects(f, b) {
    return foo.map((o, i) => ({text: f[i], number: bar[i]}))
}

console.log(makeObjects(foo, bar))
// [{text: 'aba', number: 1}, {text: 'bab', number: 2}]

Comments

0
var foo = ['aba','bab'];
var bar = [1,2];
var result = [];
function a(){
    for(var i=0;i<foo.length;i++){
        result[i] = { text: foo[i], number:bar[i]};
    }
    console.log(result);
}

is this what you are looking for?

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.