Hi guys, I have a rather interesting problem. Basically my application has a javascript object literal in this format:

var myObject = '{text:"my text 1", anotherProperty1:"This is another property1", anotherProperty2:"This is another property2", anotherProperty3:"This is another property3"},' +
'{text:"my text 2", anotherProperty1:"This is another property1", anotherProperty2:"This is another property2", anotherProperty3:"This is another property3"},'+
'{text:"my text 3", anotherProperty1:"This is another property1", anotherProperty2:"This is another property2", anotherProperty3:"This is another property3"}';

At some point I stringify it

function exportString(){
    var jsonString = JSON.stringify(myObject);
    ...
}

and jsonString contains this as expected:

[
    {"text":"my text 1", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
    {"text":"my text 2", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
    {"text":"my text 3", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"}

]

And now the problem. After I stringify it I need to add another string to it, at the very beginning, so that I end up with something like this:

[
    {"Topic":"This is my topic"},
    {"text":"my text 1", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
    {"text":"my text 2", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
    {"text":"my text 3", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"}

]

The reason why I have to do it after I stringify, is pretty long, I will try to summarize it here: my myObject is itself a property of a bigger object, and it gets updated with the Topic everytime I request it to be stringified by clicking a button: this means that if i click the button more than once, I might end up with multiple topics in the same JSON string, whereas if I do it after the object has been stringified as it is saved in a new variable, there is no problem.
Of course I tried a couple of things, played around with possible ways to add a string inside the square brackets of a JSON string but I couldn't do it, I'd always end up with something like

[
        {"Topic":"This is my topic"}
 ][
        {"text":"my text 1", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
        {"text":"my text 2", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
        {"text":"my text 3", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"}

    ]

which is not what I want.

I do have a couple of solutions of course:
1)I can create a new variable, ie local to the function, assign myObject to it and only then add the topic object to the new variable, and finally stringify it, so that I end up with only one topic each time. That would work.
2)Check that myObject doesn't contain already a topic in myObject[0], and if it doesn't, add it. This should work too.
But I'd like to see if I can inject the topic string directly inside the JSON string, do you guys think it is possible?

Member Avatar for diafol

Use unshift to add an object to the beginning of an array. Or add the string representation to the beginning of the string representation.

Member Avatar for diafol

Not sure why you're stringifying a string representation of an object though? Thought you'd want to parse with JSON.parse() to change it into an object. Confused.

Yes, apologies, copy and paste error, I meant to paste the version with stringify, I wouldn't stringify a string, lol!
Basically the application takes in a json string, then I need to turn that into an array of object literals because I need it to create abjects out of them. In the application I can add more objects and then, on demand (by clicking an Export button), I need to package all the objects inside a new json string for export. The user could the, if he wants, get the JSON string produced and use it in the application and create objects from it, it's a continuous process of parsing a string and stringify object literals.

I can't add the topic to the array. I will try to explain why. When I click on the Export button I get all the objects present in the application (they are stored in an array of literals) and convert them to JSON. So let's call this array myObject. Everytime I add a new object, this array gets update and the new object added to it. Now, when the Export button is called, Just before converting it to JSON I unshift the topic, as a new object, in it. No doubt you see the problem here: say that I press the button once to start with , everything is fine. But then I keep using the application again, I add a few objects in it, click the Export button again, and bang, now I have 2 topics objects in it. That's why I wanted to add the topic to the JSON string and not to the array of literals. As mentioned in the above thread, I do have some solutions, like creating another local variable and copy the object literals in it, then add the topic (so that everytime the Export button is clicked on, I create a new variable) and then convert to JSON.
But my question was, is it possible to somehow stringify the topic object and add it to the beginning of the JSON string in such a way that, when I parse the JSON string again, I end up with a properly formatted literal object, something like this:

[
    {"Topic":"This is my topic"},
    {"text":"my text 1", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
    {"text":"my text 2", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
    {"text":"my text 3", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"}
]

Sorry if it wasn't clear to start with.

Ah, and I have to add that the solution I described above doesn't work. To get it to work, I have to check if the zeroth element of the array has the topic already, and if not, to add it in. That works very well, but still intrigued as to whether I can implement the solution described above, in which I insert the stringified version of the topic object into the JSON string.

Member Avatar for diafol

Quick question

Can your array legitimately hold more than one object with the same property name of "topic" or can there only be one per array?

So ,in other words...

Is this allowed?

{"Topic":"This is my topic"},
{"Topic":"This is another topic"},
{"text":"my text 1", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
{"text":"my text 2", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"}, 

I'm assuming it can't, so in this case, you can loop the objects looking for property "Topic" - if it exists, don't add, if it doesn't, unshift it.

Member Avatar for diafol

Anyhow - if assumption is correct, I'd do something like this:

//INITIAL ARRAY
    var myArray = [
        {"text":"my text 1", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
        {"text":"my text 2", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
        {"text":"my text 3", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"}
    ];

//TOPIC TO ADD
var addThis = {"Topic":"This is my topic"};

//PROPERTY NAME TO CHECK
var propertyNameToCheck = "Topic";

//FUNCTION TO CHECK FOR PRESENCE OF "TOPIC" AND DECIDE TO ADD OR NOT
function checkAndAdd( arrayToCheck, objToAdd, propName) {
    var found = false;
    arrayToCheck.forEach(function(obj){
        if(obj.hasOwnProperty( propName )) {
            found = true;
            return;
        }
    });
    if(!found) arrayToCheck.unshift(objToAdd);
}

console.log(JSON.stringify(myArray));

checkAndAdd(myArray, addThis, propertyNameToCheck);
console.log(JSON.stringify(myArray));

checkAndAdd(myArray, addThis, propertyNameToCheck);
console.log(JSON.stringify(myArray));

Works for me. I would look to speed comparisions with the newer let/Set/some functions, however, I don't think it will make that much difference.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.