想要将嵌套对象转换为查询参数以附加到url

时间:2019-05-16 17:33:39

标签: javascript query-string

嗨,我需要构造带有查询参数的url请求,我有一个包含键和值的嵌套对象,如下所示

 "user": {
    "first_name": "Srini",
    "last_name": "Raman",
     "gender": "male",
     "dob": "1992-08-02",
     "address_attributes": {
      "city": "San Diego",
      "state": "CA",
      "zip": 92127,
      "country": "USA",
      "latitude": 37.257009,
      "longitude": -120.050767
    }
}


我需要获取一个查询参数

user[first_name]=Srini&user[last_name]=Raman&user[address_attributes][city]=San Diego&user[address_attributes][state]=CA

3 个答案:

答案 0 :(得分:1)

let obj = {
  user: {
    first_name: 'Srini',
    last_name: 'Raman',
    gender: 'male',
    dob: '1992-08-02',
    address_attributes: {
      city: 'San Diego',
      state: 'CA',
      zip: 92127,
      country: 'USA',
      latitude: 37.257009,
      longitude: -120.050767
    }
  }
};

let getPairs = (obj, keys = []) =>
  Object.entries(obj).reduce((pairs, [key, value]) => {
    if (typeof value === 'object')
      pairs.push(...getPairs(value, [...keys, key]));
    else
      pairs.push([[...keys, key], value]);
    return pairs;
  }, []);

let x = getPairs(obj)
  .map(([[key0, ...keysRest], value]) =>
    `${key0}${keysRest.map(a => `[${a}]`).join('')}=${value}`)
  .join('&');
console.log(x);

答案 1 :(得分:0)

使用URLSearchParams将对象转换为查询字符串,并使用Object.entries附加到查询参数中。

import org.json.JSONObject;

// code

JSONObject json = ...;
com.mypackage.JSONObject jsonObject = new com.mypackage.JSONObject(json);

答案 2 :(得分:0)

如果有人需要,这里有一个 TypeScript 实现。


const testObject = {
  "user": {
    "first_name": "Srini",
    "last_name": "Raman",
    "gender": "male",
    "dob": "1992-08-02",
    "address_attributes": {
      "city": "San Diego",
      "state": "CA",
      "zip": 92127,
      "country": "USA",
      "latitude": 37.257009,
      "longitude": -120.050767
    }
  }
}

interface ObjectToQueryStringHelperObject {
  keyPath: Array<string>;
  value: boolean | number | string;
}

function objectToQueryStringHelper(
  object: any,
  path: Array<string> = [],
  result: Array<ObjectToQueryStringHelperObject> = []
): Array<ObjectToQueryStringHelperObject> {
  return Object.entries(object).reduce((acc, [key, value]) => {
    if (!_.isNil(value) || !_.isEmpty(value)) {
      _.isObject(value) ?
        acc.push(...objectToQueryStringHelper(value, [...path, key], result)) :
        acc.push({ keyPath: [...path, key], value });
    }
    return acc;
  }, []);
}

export function objectToQueryString(object: any): string {
  const simplifiedData = objectToQueryStringHelper(object);
  const queryStrings = simplifiedData.map(({ keyPath: [firstKey, ...otherKeys], value }) => {
    const nestedPath = otherKeys.map(key => `[${key}]`).join('');
    return `${firstKey}${nestedPath}=${!_.isNil(value) ? encodeURI(`${value}`) : ''}`
  })
  return queryStrings.join('&');
}

console.log(objectToQueryString(testObject))