0

I have an array of objects, each object is similar to:

{ word: 'intentional',
  definition: 'done by intention or design',
  type: 'adjective',
  Synonyms: [  'conscious', 'deliberate', 'intended', 'knowing', ] }

I am trying to convert the whole array into following json format:

{
    "conscious": {
        "data": ["done by intention or design"],
        "type": "adjective",
        "Synonym For": ["intentional"]
    },
    "deliberate": {
        "data": ["done by intention or design"],
        "type": "adjective",
        "Synonym For": ["intentional"]
    },
    ...

}

This json format is an input to another program, which I do not control. I am running it on node.js.

How can I declare an object and then loop through the array to fill it as intended?

0

2 Answers 2

2

var obj = { word: 'intentional',
  definition: 'done by intention or design',
  type: 'adjective',
  Synonyms: [ 'conscious', 'deliberate', 'intended', 'knowing' ] },
  
  res = obj.Synonyms.reduce(function(s,a) {
    s[a] = { data: [obj.definition], type: obj.type, SynonymFor: [obj.word] };
    return s;
  }, {});
  
  console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

2
var jsonObj = {};
wordArray.forEach((word) => {
    word.Synonyms.forEach((synonym) => {
        jsonObj[synonym] = {
            data: [word.definition],
            type: word.type,
            'Synonym For': [word.word]
        };
    })
})

2 Comments

Why did you move Synonym For out of the object literal to its own statement?
I tought it won't work because of the space inside, but you are right. @zerkms

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.