如何将对象数组转换为序列化的?

时间:2018-10-13 15:24:05

标签: javascript arrays react-native serialization

我有一个对象数组

const parameters = [
  {token: '78fe6df3f'},
  {id: '12345'},
  { price: '0 - 9,000,000' },
  { 'area[]': 'Applehead Island' },
  { 'waterfront_type[]': 'Open Water' },
  { property_type_single: 'Single Family/Site Built' },
  { bedrooms: '0 - 5' },
  { baths: '0 - 5' },
  { sqft: '0 - 7500' }
];

我希望将此对象变成下面的

https://www.example.com/properties.php?token=78fe6df3f&id=12345&price=$0%20-%20$3,480,000&area[]=Applehead%20Island&waterfront_type[]=Open%20Water&property_type_single=Single%20Family/Site%20Built&bedrooms=0%20-%205&baths=0%20-%205&sqft=0%20-%207500

请帮助获取此信息?

3 个答案:

答案 0 :(得分:3)

假设这是JavaScript,则可以使用encodeURIComponent()函数对所有键值对进行URL编码,如图所示。只需遍历数组并连接URL编码的值即可:

const parameters = [
  { token: '78fe6df3f'},
  { id: '12345'},
  { price: '0 - 9,000,000' },
  { 'area[]': 'Applehead Island' },
  { 'waterfront_type[]': 'Open Water' },
  { property_type_single: 'Single Family/Site Built' },
  { bedrooms: '0 - 5' },
  { baths: '0 - 5' },
  { sqft: '0 - 7500' }
];

let uri = "https://example.org/properties.php?";
let firstSegment = true;

for(const param of parameters) {
  if(!firstSegment) {
    uri += "&";
    firstSegment = false;
  }
  
  // find out the name of this object's property
  const paramName = Object.keys(param)[0];
  uri += paramName + "=" + encodeURIComponent(param[paramName]);
}

console.log(uri);

可以使用map()join()来更简洁地写:

const parameters = [
  { token: '78fe6df3f'},
  { id: '12345'},
  { price: '0 - 9,000,000' },
  { 'area[]': 'Applehead Island' },
  { 'waterfront_type[]': 'Open Water' },
  { property_type_single: 'Single Family/Site Built' },
  { bedrooms: '0 - 5' },
  { baths: '0 - 5' },
  { sqft: '0 - 7500' }
];

let uri = "https://example.org/properties.php?" +
  parameters
    .map(
      param => {
        const name = Object.keys(param)[0];
        return name + "=" + encodeURIComponent(param[name]);
    })
    .join("&");
    
console.log(uri);

答案 1 :(得分:2)

您可以将所有对象合并为一个,遍历其属性并将其合并为一个字符串:

splice

逐步:

 const result = encodeURIComponent(Object.entries(Object.assign({}, ...parameters)).map(([key, value]) => key + "=" + value).join("&"));

1) [{ k: v }, { k2, v2 }]

Object.assign({}, ...parameters)

2) { k: v, k2: v2 }

Object.entries(...)

3) [[k, v], [k2, v2]]

.map(([key, value]) => key + "=" + value)

4) ["k=v", "k2=v2"]

.join("&")

答案 2 :(得分:2)

我在堆栈溢出中的目标是以非常简化的方式解释概念。我已在代码中进行了注释,因此您将理解每一步。

${}是ES6概念,如果您从未见过,请参考此article

感谢挑战我。

这是我解决的代码,简短易懂。

var parameters = [
      {token: '78fe6df3f'},
      {id: '12345'},
      { price: '0 - 9,000,000' },
      { 'area[]': 'Applehead Island' },
      { 'waterfront_type[]': 'Open Water' },
      { property_type_single: 'Single Family/Site Built' },
      { bedrooms: '0 - 5' },
      { baths: '0 - 5' },
      { sqft: '0 - 7500' }
    ];


    //we initialize an empty variable
    var serializedString = '';

    //.map() This loop will loop through the array to pick each object
    parameters.map((i)=>{

      //for-in This loop goes through the key-value inside of each object
      for(var key in i){

        //here we are assigning the stringed values into the variable we declared earlier on
        serializedString +=`${key}=${i[key]}&`;
      }

    });


    //after all this is done , we convert our string into a URL friendly string
    var ourURL_friendlyResult = encodeURIComponent(serializedString);

    //we console it out
    console.log(`https://example.org/properties.php?${ourURL_friendlyResult}`);