如何使用纯js中的字符串值创建带有动态键的对象?

时间:2019-09-23 12:47:50

标签: javascript

我正在尝试创建一个具有动态键的对象,该键的键ID和值是通过API获得的字符串的名称。 以下是我的API

["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"]

我想将其转换为以下响应

         [
            { id: 0, name: "PHP" },
            { id: 1, name: "Project Management" },
            { id: 2, name: "PHP dynamic website" },
            { id: 3, name: "Ecommerce" }
         ]

5 个答案:

答案 0 :(得分:2)

您可以将每个名称映射到使用索引作为id和值作为name属性的对象:

const arr = ["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"];

const res = arr.map((name, id) => ({id, name}));
console.log(res);

答案 1 :(得分:1)

只需使用forEach循环,然后将迭代器用作键:

var apiResponse = ["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"],
    newResponse = [ ];

apiResponse.forEach(function(name, index) {
   newResponse.push({ id: index, name: name });
});
 
 console.log(newResponse);

答案 2 :(得分:1)

考虑用例:假设newArr是您想要的数组类型 // ar是初始数组

ar=["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"];
newArr=[];
for(i=0;i<ar.length;i++){
  let obj={id:i,name:ar[i]};
  newArr.push(obj);
}
console.log(newArr);

答案 3 :(得分:0)

这里没有动态键,您的所有对象及其键看起来都是相同的...只需使用array.forEach()方法循环所有数组值,然后将它们推入对象,形成一个新数组:

let res = [];
sourceArr.forEach( (name, index) => {
   res.push( {id: index, name: name} );
}

那样简单。

答案 4 :(得分:0)

我用传统的方式。希望您正在寻找这个。

B = ["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"]
result = [];

for (i=0;i<B.length;i++)
{
    result[i] = "{id:"+[i]+ "name:"+B[i]+"}";
}
console.log(result);