[英]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.