246 votes

Chaine en objet en JS

J'ai une chaîne de caractères comme

string = "firstName:name1, lastName:last1"; 

maintenant j'ai besoin d'un objet obj tel que

obj = {firstName:name1, lastName:last1}

Comment puis-je faire cela en JS ?

17voto

CorySimmons Points 376

Si vous avez une chaîne comme foo: 1, bar: 2 vous pouvez le convertir en un obj valide avec :

str
  .split(',')
  .map(x => x.split(':').map(y => y.trim()))
  .reduce((a, x) => {
    a[x[0]] = x[1];
    return a;
  }, {});

Merci à niggler dans #javascript pour ça.

Mise à jour avec explications :

const obj = 'foo: 1, bar: 2'
  .split(',') // split into ['foo: 1', 'bar: 2']
  .map(keyVal => { // go over each keyVal value in that array
    return keyVal
      .split(':') // split into ['foo', '1'] and on the next loop ['bar', '2']
      .map(_ => _.trim()) // loop over each value in each array and make sure it doesn't have trailing whitespace, the _ is irrelavent because i'm too lazy to think of a good var name for this
  })
  .reduce((accumulator, currentValue) => { // reduce() takes a func and a beginning object, we're making a fresh object
    accumulator[currentValue[0]] = currentValue[1]
    // accumulator starts at the beginning obj, in our case {}, and "accumulates" values to it
    // since reduce() works like map() in the sense it iterates over an array, and it can be chained upon things like map(),
    // first time through it would say "okay accumulator, accumulate currentValue[0] (which is 'foo') = currentValue[1] (which is '1')
    // so first time reduce runs, it starts with empty object {} and assigns {foo: '1'} to it
    // second time through, it "accumulates" {bar: '2'} to it. so now we have {foo: '1', bar: '2'}
    return accumulator
  }, {}) // when there are no more things in the array to iterate over, it returns the accumulated stuff

console.log(obj)

Documents MDN confus :

Démonstration : http://jsbin.com/hiduhijevu/edit?js,console

Fonction :

const str2obj = str => {
  return str
    .split(',')
    .map(keyVal => {
      return keyVal
        .split(':')
        .map(_ => _.trim())
    })
    .reduce((accumulator, currentValue) => {
      accumulator[currentValue[0]] = currentValue[1]
      return accumulator
    }, {})
}

console.log(str2obj('foo: 1, bar: 2')) // see? works!

13voto

Grigor IWT Points 109

Vous devez utiliser JSON.parse() pour convertir une chaîne en objet :

var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');

12voto

mzalazar Points 645

Si vous utilisez JQuery :

var obj = jQuery.parseJSON('{"path":"/img/filename.jpg"}');
console.log(obj.path); // will print /img/filename.jpg

RAPPEL : l'évaluation est un mal ! :D

5voto

Rodu Points 111

J'ai mis en place une solution en quelques lignes de code qui fonctionne de manière assez fiable.

J'ai un élément HTML comme celui-ci où je veux passer des options personnalisées :

<div class="my-element"
    data-options="background-color: #dadada; custom-key: custom-value;">
</div>

une fonction analyse les options personnalisées et retourne un objet pour les utiliser quelque part :

function readCustomOptions($elem){
    var i, len, option, options, optionsObject = {};

    options = $elem.data('options');
    options = (options || '').replace(/\s/g,'').split(';');
    for (i = 0, len = options.length - 1; i < len; i++){
        option = options[i].split(':');
        optionsObject[option[0]] = option[1];
    }
    return optionsObject;
}

console.log(readCustomOptions($('.my-element')));

5voto

ben Points 31

Dans votre cas, le code court et beau

Object.fromEntries(str.split(',').map(i => i.split(':')));

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X