skip to Main Content

how to update all keys an object by getting an array witch have keys that we want
Example :

const data = {
0 : {text : 'hello'},
1 : {text : 'hi'},
2 : {text : 'hay!'} 
}
function arrayCombine(keys , values){
...logics
}
console.log(arrayCombine([10 , 20 , 37] , data));

// resault
{
10 : {text : 'hello'},
20 : {text : 'hi'},
37 : {text : 'hay!'} 
}

This function gets an array and an object then performs an operation on the object and change all the keys of the object to that array’s element.
In the php we have a built-in function witch is called array_combine
.

2

Answers


  1. If I understood correctly, below logic should works

    const data = {
      0: { text: 'hello' },
      1: { text: 'hi' },
      2: { text: 'hay!' },
    };
    function arrayCombine(keys, values) {
      const valuesArray = Object.values(values);
      let result = {};
      keys.forEach((item, index) => (result[item] = valuesArray[index]));
      return result;
    }
    console.log(arrayCombine([10, 20, 37], data));
    Login or Signup to reply.
  2. const data = {
      0: {
        text: 'hello'
      },
      1: {
        text: 'hi'
      },
      2: {
        text: 'hay!'
      },
    };
    
    function arrayCopy(keys, values) {
      const valuesArray = Object.values(values);
      return keys.map((e, i) => ({
        [e]: valuesArray[i]
      }));
    }
    console.log(arrayCopy([10, 20, 37], data));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search