TradingPal / react-native-highcharts

📈 Add Highcharts charts to react-native app for IOS and Android
https://github.com/TradingPal/react-native-highcharts
256 stars 158 forks source link

0 length array not handled correctly by flattenText #35

Open cmprescott opened 7 years ago

cmprescott commented 7 years ago

Error can be seen running the following javascript

var flattenObject = function (obj, str='{') {
    Object.keys(obj).forEach(function(key) {
        str += `${key}: ${flattenText(obj[key])}, `
    })
    return `${str.slice(0, str.length - 2)}}`
};

var flattenText = function(item) {
    var str = ''
    if (item && typeof item === 'object' && item.length == undefined) {
        str += flattenObject(item)
    } else if (item && typeof item === 'object' && item.length !== undefined) {
        str += '['
        item.forEach(function(k2) {
            str += `${flattenText(k2)}, `
        })
        str = str.slice(0, str.length - 2)
        str += ']'
    } else if(typeof item === 'string' && item.slice(0, 8) === 'function') {
        str += `${item}`
    } else if(typeof item === 'string') {
        str += `\"${item.replace(/"/g, '\\"')}\"`
    } else {
        str += `${item}`
    }
    return str
};

var testJson = {
  happyJsonArray: ['one', 'deux', 'tres'],
  incorrectlyHandledJsonArray: []
};

console.log(flattenText(testJson));
// VM207:34 {happyJsonArray: ["one", "deux", "tres"], incorrectlyHandledJsonArray: ]}

Is there a reason y'all use flattenText() & flattenObject() instead of just keeping config from JSON.stringify?

Infinity0106 commented 6 years ago

because we can not stringify a function inside the object, we have to treat functions different. thanks in advance for using the component

droidMakk commented 2 years ago

applied a check for the last element & improvised an array check now it works fine Fixes #35

var flattenObject = function (obj, str='{') {
    const keys = Object.keys(obj)
    keys.forEach(function(key, idx) {
        str += idx === (keys.length - 1) ? `${key}: ${flattenText(obj[key])}` : `${key}: ${flattenText(obj[key])},`
    })
    return `${str}}`
};

var flattenText = function(item) {
    var str = ''
    if (item && typeof item === 'object' && !Array.isArray(item)) {
        str += flattenObject(item)
    } else if (Array.isArray(item)) {
        str += '['
        item.forEach(function(k2, idx) {
            str += idx === (item.length - 1) ? flattenText(k2) : `${flattenText(k2)},`
        })
        // str = str.slice(0, str.length - 2)
        str += ']'
    } else if(typeof item === 'string' && item.slice(0, 8) === 'function') {
        str += `${item}`
    } else if(typeof item === 'string') {
        str += `\"${item.replace(/"/g, '\\"')}\"`
    } else {
        str += `${item}`
    }
    return str
};

var testJson = {
  happyJsonArray: ['one', 'deux', 'tres'],
  incorrectlyHandledJsonArray: [],
  anotherEmptyObject: {}
};