javascript 如何在Nodejs中从列表中动态获取密钥名称

np8igboo  于 2023-06-04  发布在  Java
关注(0)|答案(4)|浏览(104)

如何从列表中动态获取键名,并使用NodeJS将其推送到数组中。
这是我的字符串{ PRICE: '12', TYPE: 'Electronics' }
我想把键名PRICETYPE推到一个array,如下所示:

const myArray = ["PRICE", "MyOrg::PRICE", "TYPE", "MyOrg::TYPE"]

我不知道如何从列表中动态获取密钥名称并将其推送到数组中-有人可以帮助我吗?谢谢

示例代码:

const test = async () => {

        const myList =  { TYPE: '12', REGION: 'Electronics' }

        // Execpted array like below
        const myArray = ["PRICE", "MyOrg::PRICE", "TYPE", "MyOrg::TYPE"]

  };
  
  test();
sulc1iza

sulc1iza1#

您可以简单地使用Object.keys执行Array.concat

const myList = { TYPE: '12', REGION: 'Electronics' };
let myArray = ['PRICE', 'MyOrg::PRICE'];

myArray = myArray.concat(Object.keys(myList));
console.log(myArray);
niwlg2el

niwlg2el2#

你只需要在你的代码中使用variable substitution,你可以用花括号括起变量,就像这样${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)
tmb3ates

tmb3ates3#

这个问题没什么意义下面的代码生成了您所要求的输出,但似乎没有什么用处。

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"]
vfhzx4xs

vfhzx4xs4#

您可以将reduceconcat一起使用

const myList =  { TYPE: '12', REGION: 'Electronics' }
 
const  results = Object.keys(myList).reduce(
                        (a, b) => a.concat([b, "My0rg::" + b]), []);

console.log(results)

相关问题