Unable to add an array index

Viewed 79

I would like to allocate names for the index in an array while using for loop. how can i achieve this. please guide me.

// using in a http response
   for (let i = 0; i <= 6; i++) {
            this.sf.push({f(i) : // do something)
          };

i want to get something like

f0: 1,
f1: 5,
f2: 9
5 Answers

Do you want to turn the array, [1,5,9,...], into an object, {f0: 1, f1: 5, f2:9, ...}?

If so, you can use Array.reduce() for the conversion:

const test = [1,5,9,10,15,25]; 

const result = test.reduce((accum, elem, index) => {
  accum[`f${index}`] = elem;
  return accum;

}, {});

UPDATE:

Turns out, you can use the same method to keep it as an Array:

const arrayResult = test.reduce((accum, elem, index) => {
  accum[`f${index}`] = elem;
  return accum;

}, []);

arrayResult; // [f0: 1, f0: 5, ...]

Source

You will need to transform the array into an object. Here is a sample code:

let test = [1,5,9,10,15,25];
let obj  = {};
for (let i = 0; i<test.length; i++) {
  obj["f" + i] = test[i];
}
console.log(JSON.stringify(obj)); // prints {"f0":1, "f1":5, "f2":9, "f3":10, "f4":15, "f5":25}

My approach would be a little different from other answers. I would prefer using Object.entries as this is more clear and explicit.

const sf = {}
const arr = [1,2,3,4,5,6]
for (let [key, value] of Object.entries(arr)) {
  sf[`f${key}`] = value
}
console.log(sf);

You can use map function for that. Such as:

test = [1,5,9,10,15,25];
new_arr = [];
test.map(function(element, index) {new_arr.push('f'+index+':'+element);})
console.log(new_arr);

Try this:

         for( const [key, value] of Object.entries(test)){
                let obj= {};
                obj['f' +key] = value;
                this.sf.push(obj);
                    }
Related