简体   繁体   English

如何在JavaScript对象中将数组设置为键值?

[英]How can I set array as a key value in javascript object?

I am trying to set an array as a key value in a JSON object using javascript. 我正在尝试使用javascript将数组设置为JSON对象中的键值。

When I set the array value, 当我设置数组值时

console.log(obj["likes"]) displays an array of size 1. console.log(obj [“ likes”])显示大小为1的数组。

but on the next line console.log(obj) shows that the likes key is an array of size 0. 但在下一行console.log(obj)显示Likes键是大小为0的数组。


I have a JSON object that has information about posts. 我有一个有关帖子信息的JSON对象。

If no likes exist on a post then that field does not exist in that post's objects. 如果帖子中不存在喜欢的对象,则该字段在该帖子的对象中不存在。

I am trying to implement a like-dislike update function, where I check if a user has liked a post. 我正在尝试实现一个不喜欢的更新功能,该功能用于检查用户是否喜欢帖子。

If he hasn't then I append his username to the array of likes else I remove his username. 如果他还没有,那么我将他的用户名附加到喜欢的数组中,否则我将删除他的用户名。

userID is a global variable that I define at the start of the script tag. userID是我在脚本标记开头定义的全局变量。

It works if instead of userID, I set a new string like: 如果我设置一个新的字符串而不是userID,那么它将起作用:

obj["likes"] = ["XX"]

This works too (i get an extra space but it atleast logs correctly): 这也可以工作(我得到一个额外的空间,但至少可以正确记录日志):

obj["likes"] = [userId+" "]
console.log(obj["likes"])
console.log("Obj:",obj)

But then doing this again does not work!!!! 但是,然后再做一次是行不通的!!!!

let arr = [" "+userId]
console.log(arr)
arr[0] = arr[0].trim()
console.log(arr)
obj["likes"] = arr
console.log("Obj:",obj)
function saveLikeDislike(url, action) {
        for (i = 0; i < crawledUrlsData.length; i += 1) {

            if (typeof crawledUrlsData[i] === "object") {

                var obj = crawledUrlsData[i]

                if (url === obj["url"]) {

                    if (action === "like") {

                        if ("likes" in obj) {
                            likes = obj["likes"]
                            if (likes.includes(userId)) {
                                likes = likes.filter(id => id != userId)
                            } else {
                                likes.push(userId)
                            }
                            obj["likes"] = likes
                        } else {
                            var id = window.userId
                            console.log(userId)

                            obj["likes"] = [id]
                            console.log(obj["likes"])
                            console.log("Obj:",obj)
                        }

                        if ("dislikes" in obj) {
                            var dislikes = obj["dislikes"]

                            if (dislikes.includes(userId)) {
                                dislikes = dislikes.filter(id => id != userId)
                                obj["dislikes"] = dislikes
                            }
                        }

                    } else {

                        if ("dislikes" in obj) {
                            dislikes = obj["dislikes"]
                            if (dislikes.includes(userId)) {
                                dislikes = dislikes.filter(id => id != userId)
                            } else {
                                dislikes.push(userId)
                            }
                            obj["dislikes"] = dislikes
                        } else 
                            obj["dislikes"] = [dislikes]
                        }

                        if ("likes" in obj) {
                            var likes = obj["likes"]

                            if (likes.includes(userId)) {
                                likes = likes.filter(id => id != userId)
                                obj["likes"] = likes
                            }
                        }
                    }

                    crawledUrlsData[i] = obj
                    console.log(obj["likes"])

                    renderData()
                    return
                }
        }
    }

控制台输出

Two problems. 两个问题。 1. That usrId - userId typo randomSoul has mentioned. 1.提到usrId-userId错字。 2. This line: 2.此行:

likes = likes.push(userId)

The output of likes.push(something) is a number, the length of the array after push. likes.push(something)的输出是一个数字,即推送后数组的长度。 This line will amount to likes = 1 . 该行总计为likes = 1 Do instead: 改为:

likes.push(userId)

push returns the new length of the array - so this line: push返回数组的新长度-所以这一行:

likes = likes.push(userId);

Will be a number, not an array - remove the assignment: 将是数字,而不是数组-删除分配:

likes.push(userId);

Turnes out I had missed a parenthesis. 原来我错过了括号。

But this still does not explain the odd behavior where on one line key value was set and the very next line the output from console.log was different when accessing userId but proper if userId was modified in some way. 但这仍然不能解释在访问userId时在一行上设置键值而在下一行中console.log输出不同的奇怪行为,但是如果以某种方式修改了userId则正确。

Anyway, here's the fixed function: 无论如何,这是固定功能:

function saveLikeDislike(url, action) {
    for (i = 0; i < crawledUrlsData.length; i += 1) {

        if (typeof crawledUrlsData[i] === "object" && crawledUrlsData[i]["url"] == url) {

            var obj = crawledUrlsData[i]

            if (url === obj["url"]) {

                if (action === "like") {

                    if ("likes" in obj) {
                        console.log("likes in obj")
                        likes = obj["likes"]
                        if (likes.includes(userId)) {
                            likes = likes.filter(id => id != userId)
                        } else {
                            likes.push(userId)
                        }
                        obj["likes"] = likes
                    } else {

                        obj.likes = [userId]
                        console.log("Obj:",obj)
                    }

                    if ("dislikes" in obj) {
                        var dislikes = obj["dislikes"]
                        console.log("Dislikes: ",dislikes)
                        if (dislikes.includes(userId)) {
                            dislikes = dislikes.filter(id => id != userId)
                            obj["dislikes"] = dislikes
                        }
                    }

                } else if (action === "dislike"){

                    if ("dislikes" in obj) {
                        dislikes = obj["dislikes"]
                        if (dislikes.includes(userId)) {
                            dislikes = dislikes.filter(id => id != userId)
                        } else {
                            dislikes.push(userId)
                        }
                        obj["dislikes"] = dislikes
                    } else {
                        obj["dislikes"] = [userId]
                    }
                    if ("likes" in obj) {
                        var likes = obj["likes"]
                        console.log("ID: ",userId)
                        if (likes.includes(userId)) {
                            likes = likes.filter(id => id != userId)
                            obj["likes"] = likes
                        }
                    }
                }    
            }

                crawledUrlsData[i] = obj

                linkTreeRef.set(crawledUrlsData)
        }
    }
}

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

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