简体   繁体   English

如何将具有两个键/值对的对象推入数组?

[英]How to push an object with two key/value pairs into an array?

I want to take this array as an argument 我想将此数组作为参数

var movies = ['matrix','the dark knight','a beautiful mind','american pie']

for a function that loops through that array and pushes the titles as object into a new array adding an id (from the loop index) along the way. 用于循环遍历该数组并将标题作为对象推入新数组的函数,并在此过程中添加一个ID(来自循环索引)。

The new arr should look like this 新的arr应该看起来像这样

['{title:matrix, id:0}','{title:the dark knight, id:1}','{title:a beautiful mind, id:2}','{title:american pie, id:3}']

This is the function and I know I have a syntax error. 这是函数,我知道我有语法错误。 But where? 但是哪里?

function addToList(arr) {
    var movieList = []

    for (var x of arr) {
        movieList{["titel"]=arr, ["id"]=x}
    }
    return movieList
}

You can simply use .map() to get the desired output: 您可以简单地使用.map()获得所需的输出:

 const data = ['matrix','the dark knight','a beautiful mind','american pie'] const result = data.map((m, i) => ({title: m, id: i})); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Without using array.map 不使用array.map

 function addToList(arr) {
        var movieList = []

        for (var i in arr) {
            movieList[i]={title:arr[i], id:i}
        }
        return movieList
    }

OR 要么

function addToList(arr) {
    var movieList = []

    for (var i in arr) {
        movieList.push({title:arr[i], id:i});
    }
    return movieList
}

 function addToList(arr) { var movieList = [] for (var x of arr) { movieList.push({titel: arr, id: x}); } return movieList } 

for...of statement iterates over values of the object, not the indices (properties). for ... of语句遍历对象的值,而不遍历索引(属性)。

You can use for...in statement to iterate over indices (properties) of the object. 您可以使用for ... in语句遍历对象的索引(属性)。

 var movies = ['matrix','the dark knight','a beautiful mind','american pie']; function addToList(arr) { var movieList = []; for (var i in arr) { movieList[i] = {"title": arr[i], "id": i}; } return movieList; } console.log(addToList(movies)); 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM