0

I have an array of words. I am not getting how can I convert each word into json by using JavaScript?

Here is the piece of code that I am using:

this.new_testing = [];
      this.newcontent=Contents.split(' ');
      console.log(this.newcontent, 'word count')
      console.log(JSON.stringify({newtesting : this.newcontent}), 'word count json');
      console.log(this.new_testing.push(this.newcontent) , ' all push list')
      console.log(this.new_testing, ' string testing')
0

2 Answers 2

2
sentence = 'there is nothing happening';
words = sentence.split(' ');
wordList = words.map((word,index) => {
    return {
        word,
        color: logicForColor(index, words)
    }

});

function logicForColor(index, words) {
    return index ===0 ? 'RED': index===words.length-1 ? 'BLUE' : '';
}

console.log('WList:', wordList)

Outputs

0: {word: "there", color: "RED"}
1: {word: "is", color: ""}
2: {word: "nothing", color: ""}
3: {word: "happening", color: "BLUE"}
Sign up to request clarification or add additional context in comments.

Comments

0

You must determine your color of word yourself

var str = "There is nothing happening"; 
var splitted = str.split(" "); 
splitted.forEach(i=>{
  let dataObject: any = {
    word: i,
    color: 'red'
  };

  let dataObjectSpace: any = {
    word: ' ',
    color: 'red'
  };

  this.dataObjectList.push(dataObject);
  this.dataObjectList.push(dataObjectSpace);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.