ajmajmajma
ajmajmajma

Reputation: 14216

Creating string out of object in JavaScript

I am trying to assemble a certain string out of a JavaScript object and am having some problems.

I created a function that takes the object and should return the string. The initial object looks like so:

var testObject = {
  "Topics": ["Other", "New1"],
  "Other": ["try this", "this also"]
};

And I would like the string to spit out this:

"Topics~~Other|Topics~~New1|Other~~try this|Other~~this also"

Here is what I have now:

var testObject = {
  "Topics": ["Other", "New1"],
  "Other": ["try this", "this also"]
};

function transformObjectToString(activeFilters) {
  var newString = "";

  var checkFilterGroups = function(filterTopic) {
    activeFilters[filterTopic].map(function(selectedFilter) {
      var tempString = filterTopic + "~~" + selectedFilter + "|";
      console.log("check string", tempString);
      newString.concat(tempString);
    });
  }

  for (var filterGroup in activeFilters) {
    checkFilterGroups(filterGroup);
  }

  return newString;

}

console.log(transformObjectToString(testObject));

The temp string seems to be formatted correctly when I check the log, but, for whatever reason, it looks like the concat is not working as I assumed it would.

Upvotes: 0

Views: 85

Answers (3)

some_groceries
some_groceries

Reputation: 1192

newString = newString.concat(tempString);

this works too.

edit: how this works is, at first newString is set to null so null + tempstring at first loop, and then the newSting is set to a value, value + tempString on second loop and so on. finally you have the concatinated string in one variable which you will be returning.

edit:edit: Also what @jfriend00 said in the comments, ditto

.concat() returns a new string so newString.concat(tempString); is not accomplishing anything because you don't assign the result back to newString. Remember, strings in Javascript are immutable so any modification always creates a new string

Upvotes: 1

Fabricator
Fabricator

Reputation: 12772

You can use .join('|')

var testObject = {
  "Topics": ["Other", "New1"],
  "Other": ["try this", "this also"]
};

function transformObjectToString(activeFilters) {
  var strings = [];

  var checkFilterGroups = function(filterTopic) {
    activeFilters[filterTopic].map(function(selectedFilter) {
      var tempString = filterTopic + "~~" + selectedFilter;
      strings.push(tempString);
    });
  }

  for (var filterGroup in activeFilters) {
    checkFilterGroups(filterGroup);
  }

  return strings.join('|');

}

console.log(transformObjectToString(testObject));

Upvotes: 1

John Fish
John Fish

Reputation: 1085

You should be able to just use += as this is just string concatenation. Then, all you must do is strip the last character. Here's a JSFiddle with the change https://jsfiddle.net/tfs98fxv/37/.

Upvotes: 4

Related Questions