-1

I have to convert project[maximum_contract_amount_estimated_completion_date] to project.maximum_contract_amount_estimated_completion_date.

The problem is, i m getting project[maximum_contract_amount_estimated_completion_date] through api in a variable and it can be anything like project[blablabla]. So i want to apply global solution for all types of values like this.

I have this:

var json = {
    'key': 'project[maximum_contract_amount_estimated_completion_date]',
    'value': '2017-02-22'
};

Now what i need to do is call the API and send data as

var project = {}; project['maximum_contract_amount_estimated_completion_date'] = '2017-02-22';

I tried JSON.parse but it didn't work.

Can anyone please help me out here. I m new to this.

Thanks

Ravinder Singh
  • 173
  • 1
  • 1
  • 9
  • the first doesn't look like valid anything ... and what you want doesn't look useful (what value should it be?) ... and, as shown, this has absolutely nothing to do with JSON – Jaromanda X Feb 22 '17 at 11:09
  • I want to post project.maximum_contract_amount_estimated_completion_date as JSON key in api. I m getting project[maximum_contract_amount_estimated_completion_date] from another API. – Ravinder Singh Feb 22 '17 at 11:12
  • 1
    you still have only described about 10% of your problem – Jaromanda X Feb 22 '17 at 11:13
  • can you post the result of `JSON.stringify(project)` ? – StefansArya Feb 22 '17 at 11:13
  • Possible duplicate of [Is it possible to add dynamically named properties to JavaScript object?](http://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – Rajesh Feb 22 '17 at 11:14
  • @Rajesh it's not duplicate. Please check my updated explanation in the question. – Ravinder Singh Feb 22 '17 at 11:17
  • @JaromandaX, I have added more explanation in the question. Please check it. – Ravinder Singh Feb 22 '17 at 11:18
  • none of the code you've posted is valid javascript - so, it's hard to understand the data you want to "convert" – Jaromanda X Feb 22 '17 at 11:18
  • @RavinderSingh first its still unclear. Try giving sample. Secondly it still looks like adding dynamic property to object – Rajesh Feb 22 '17 at 11:19
  • @JaromandaX I added more explaination with example in question. Please check it. – Ravinder Singh Feb 22 '17 at 11:32
  • the issue is that string `project[maximum_contract_amount_estimated_completion_date]` is a string, and it's not an array, at all, in no sense of the word array with respect to javascript – Jaromanda X Feb 22 '17 at 11:46

1 Answers1

0

A generic way would be

var json = {
    'key': 'project[maximum_contract_amount_estimated_completion_date]',
    'value': '2017-02-22'
};
var a = json.key.match(/^(.*)\[(.*)\]/);
window[a[1]] = window[a[1]] || {};
window[a[1]][a[2]] = json.value;
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87