简体   繁体   中英

How to fill and object with data from an array in javascript

Really, the question is how to fill and object with data from a string, but string to array is trivial.

I need to end up with an object thus:

myobject={"x":5,"y":6,"w":7,"h":8}

starting from a string, thus:

var str = "5 6 7 8"

My solutions so far are

var myarray = str.split(' ');
var myobject = {
    x : myarray[0],
    y : myarray[1],
    w : myarray[2],
    h : myarray[3]
}

or

var myarray = str.split(' ');
var mynames = ['x','y',' w','h'];
 for (var i = mynames.length - 1; i >= 0; i--) {
    obj.[mynames[i]]=myarray[i]
 }

Wonder if there is a better way

Array.prototype.reduce is your friend:

var myarray = str.split(' ');
var mynames = ['x','y',' w','h'];

var obj = myarray.reduce((acc, curr, i) => {
  acc[mynames[i]] = curr
  return acc
}, {})  // => {"x":5,"y":6,"w":7,"h":8}

acc is your accumulator object (your new output), and curr (current) is the current item in myarray .

This is dependent on the order of the items in your string that you're splitting, as well as the order of mynames .

Edit: this solution is compatible with ES6 and ES5 (if you use a regular function(){} as the callback instead of an arrow function).

I would use destructuring to assign the numbers to variables, and then assign them to the object using shorthand property names .

 const str = "5 6 7 8"; const [x, y, w, h] = str.split(' '); const obj = { x, y, w, h }; console.log(obj); 

One option is using ES 6 destructuring . Destructuring allows assigning multiple values in a single statement. Also, spread syntax can be used for spreading the string to an array.

 var outputObj = {x:'', y : '', w : '', h: ''}; var stringToConvert = "5678"; [outputObj.x, outputObj.y, outputObj.w, outputObj.h] = [...stringToConvert]; console.log(outputObj); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM