简体   繁体   English

如何将config.properties转换为键值对?

[英]How to convert config.properties into key value pairs?

I am trying to convert a java properties file into a key value pairs that I can use in jquery. 我正在尝试将Java属性文件转换为可在jquery中使用的键值对。 The property file sends information that looks like this: 属性文件发送的信息如下所示:

company1=Google
company2=eBay
company3=Yahoo

And I want it in this form: 我想要这种形式:

var obj = {
 company1: Google,
 company2: ebay,
 company3: Yahoo
};

I am going to be accessing the property file through a URL. 我将通过URL访问属性文件。

Assuming your file comes exactly the way you've pasted it here, I would approach it something like this: 假设您的文件恰好是您在此处粘贴的方式,那么我将采用以下方式进行处理:

 var data = "company1=Google\\ncompany2=eBay\\ncompany3=Yahoo"; var formattedData = data // split the data by line .split("\\n") // split each row into key and property .map(row => row.split("=")) // use reduce to assign key-value pairs to a new object // using Array.prototype.reduce .reduce((acc, [key, value]) => (acc[key] = value, acc), {}); var obj = formattedData; console.log(obj); 

This post may be helpful if you need to support ES5 Create object from array 如果你需要支持ES5这篇文章可能会有所帮助从阵列中创建对象

Just use npm module https://www.npmjs.com/package/properties 只需使用npm模块https://www.npmjs.com/package/properties

This module implements the Java .properties specification and adds additional features like ini sections, variables (key referencing), namespaces, importing files and much more. 该模块实现Java .properties规范,并添加了其他功能,如ini节,变量(键引用),名称空间,导入文件等等。

# file
compa = 1
compb = 2


nodejs:

var properties = require ("properties");

properties.parse ("file.properties", { path: true }, function (error, obj){
  if (error) return console.error (error);

  console.log (obj);
  //{ compa : 1, compb : 2 }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将对象的属性和值转换为键值对数组 - Convert object's properties and values to array of key value pairs 如何使用键值对将字符串转换为 object - How to convert string into object with key value pairs 如何将对象数组转换为键值对 - How to convert an array of objects into key value pairs 将数组对象键值对属性转换为单个键值对,然后将其再次插入数组 - Convert Array Objects key value pairs properties to a single key value pair and insert it into array again 如何在服务器端而非客户端的JAVA中逐行从config.properties文件读取数据 - How to read data from config.properties file line by line in JAVA on the server side not on the client side 将键/值对转换为 json - Convert Key/Value pairs to json 如何访问使用 = 而不是键值对的 object 中的属性 - How to access the properties in an object that uses = instead of key value pairs 如何使用映射的键值对将数组转换为javascript中的对象? - How to convert an array into an object in javascript with mapped key-value pairs? 如何在JavaScript中将多个对象转换为键值对数组[] - How to convert multiple Objects to an Array [] of key-value pairs in javascript 如何在 JavaScript 中将嵌套对象数组转换为具有键值对的对象 - How to convert an array of nested objects to an object with key, value pairs in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM