2017-08-19 27 views
-2

Ich habe Daten in unordinary Format const variations konvertiert Klartext in Objekt

const variations = { 
 
    0: "{"productPriceLocal": "16990.00", "productId": "30028132"}", 
 
    1: "{"productPriceLocal": "22990.00", "productId": "30028233"}" 
 
}; 
 

 
// this code doesn't work 
 
// console.log(_.map(variations, 'productId'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

und ich möchte dies so zu normalen JS Objekt konvertieren, die mit mir normalerweise

const object = { 
 
    0: { 
 
    productId: 30028132, 
 
    ... 
 
    }, 
 
    ... 
 
}
arbeiten kann

Ich habe versucht, l zu verwenden Odash, funktioniert nicht gut. Weiß jemand, was ich tun soll?

+1

"{" productPriceLocal ": "16.990,00", "productId": "30028132"}", dies keine gültige Zeichenfolge oder ein Objekt – marvel308

+1

Verwenden JSON.parse() wie hier erklärt : https://www.w3schools.com/js/js_json_parse.asp – IngoB

Antwort

2

Das erste Problem, das Sie haben, ist, dass "{"productPriceLocal": "16990.00", "productId": "30028132"}" enthält unescaped Anführungszeichen, die die Zeichenfolge beenden, bevor Sie es wollen (was zu Fehlern). Also, wenn Sie diese Zeichenfolge mit einfachen Anführungszeichen enthalten, sollte Ihr erstes Problem behoben sein.

Dann Parsen der JSON-Objekte wie unten getan sollte die Ausgabe, die Sie suchen, keine lodash erforderlich.

const variations = { 
 
    0: '{"productPriceLocal": "16990.00", "productId": "30028132"}', 
 
    1: '{"productPriceLocal": "22990.00", "productId": "30028233"}' 
 
}; 
 

 
var output = {}; 
 

 
for(key in variations) { 
 
    output[key] = JSON.parse(variations[key]); 
 
} 
 

 
console.log(output);

1

Sie Array reduce und Object.keys Methoden verwenden, könnte Ihr Objekt auf ein einzelnes Objekt vom Typ wollen Sie abzubilden.

//Make sure you escape the quotes in your JSON strings. 
 
const variations = { 
 
     0: "{\"productPriceLocal\": \"16990.00\", \"productId\": \"30028132\"}", 
 
     1: "{\"productPriceLocal\": \"22990.00\", \"productId\": \"30028233\"}" 
 
    }; 
 

 
let parsedValues = Object.keys(variations) // Get keys as an array [0,1] 
 
    .reduce((obj, key) => { 
 
     // parse to an object. 
 
     obj[key] = JSON.parse(variations[key]); 
 
     return obj; 
 
    }, {} /* initialization object */); 
 
console.log(parsedValues);

Verwandte Themen