3

I have 2 array, one for key and other for value.

Want create new array with these arrays.

key: [01, 02, 03]
value: ["hi", "hello", "welcome"]
Output I need:

[ 
  {"key": "1","value":"hi"},
  {"key": "2","value":"hello"},
  {"key": "3","value":"welcome"} 
]    

How to get result by this way.?

My code:

output = key.map(function(obj, index){
      var myObj = {};
      myObj[value[index]] = obj;
      return myObj;
    })    

Result:

 [
 {"1","hi"},
 {"2","hello"},
 {"3","welcome"} 
    ]
0

4 Answers 4

5

const keys = [01, 02, 03];
const values = ['hi', 'hello', 'welcome'];

const res = keys.map((key, ind) => ({ 'key': ''+key, 'value': values[ind]}));
console.log(res);

There is also a proposal for the following method of Object, fromEntries, which will do exactly what you want to, but it is not supported yet by the major browsers:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

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

Comments

1

    var myArray = [];  
    var keys = [45, 4, 9];  
    var cars = ["Saab", "Volvo", "BMW"];  
    cars.forEach(myFunction);  
    var txt=JSON.stringify(myArray);  
    document.getElementById("demo").innerHTML = txt;  
      
    function myFunction(value,index,array) {  
        var obj={ key : keys[index], value : value };  
        myArray.push(obj);  
    }  
    <p id="demo"></p>  

Comments

0

You could take an object with arbitrary count of properties amd map new objects.

var key = [1, 2, 3],
    value = ["hi", "hello", "welcome"],
    result = Object
        .entries({ key, value })
        .reduce((r, [k, values]) => values.map((v, i) => Object.assign(
            {},
            r[i],
            { [k]: v }
        )), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

Here you have another apporach using reduce():

let keys = [01, 02, 03];
let values = ['hi', 'hello', 'welcome'];

let newArray = keys.reduce((res, curr, idx) => {
    res.push({'key': curr.toString(), 'value': values[idx]});
    return res;
}, []);

console.log(newArray);

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.