[英]How to get the key name dynamically from the list in Nodejs
How to get the key name dynamically from the list and push it to an array using NodeJS.如何从列表中动态获取键名并使用 NodeJS 将其推送到数组。
This is my string { PRICE: '12', TYPE: 'Electronics' }
这是我的字符串{ PRICE: '12', TYPE: 'Electronics' }
I want to push the key name PRICE
, TYPE
to an array
like below:我想将键名PRICE
, TYPE
推送到如下所示的array
:
const myArray = ["PRICE", "MyOrg::PRICE", "TYPE", "MyOrg::TYPE"]
I don't know how to get the key name dynamically from the list and push it to an array - can someone pls help me with this.我不知道如何从列表中动态获取键名并将其推送到数组中 - 有人可以帮我解决这个问题吗? Thanks.谢谢。
Sample code:示例代码:
const test = async () => {
const myList = { TYPE: '12', REGION: 'Electronics' }
// Execpted array like below
const myArray = ["PRICE", "MyOrg::PRICE", "TYPE", "MyOrg::TYPE"]
};
test();
You could simply do Array.concat
with Object.keys
你可以简单地用Object.keys
做Array.concat
const myList = { TYPE: '12', REGION: 'Electronics' }; let myArray = ['PRICE', 'MyOrg::PRICE']; myArray = myArray.concat(Object.keys(myList)); console.log(myArray);
Question doesn't really make sense.问题真的没有意义。 The following code generates the output that you are asking for, but it doesn't seem useful.以下代码生成您要求的输出,但它似乎没有用。
const myList = { "PRICE": 12, "TYPE": "Electronic" }; const myArray = []; Object.keys(myList).forEach( function (key) { // Loop through all the keys myArray.push(key) myArray.push("MyOrg::"+key) }) console.log(myArray) // Expected output // myArray == ["PRICE", "MyOrg::PRICE", "TYPE", "MyOrg::TYPE"]
You just need variable substitution in your code, that you get by enclosing variable with curly braces like this ${variable}
.你只需要在你的代码中进行变量替换,你可以通过像${variable}
这样的花括号括起${variable}
。
const myList = { TYPE: '12', REGION: 'Electronics' } array = Object.keys(myList) myArray = [] for (let element of array){ myArray.push(element, `MyOrg::${element}`) } console.log(myArray)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.