Object对象数组Json.字符串数组的字符串化

Object Obect array Json.stringify string array

本文关键字:数组 字符串 Json 对象 Object      更新时间:2023-09-26

我有一个对象对象数组,我使用JSON.stringify(),我现在可以看到我的数组中有什么,但当我做arr[0]等时,它只输出一个字母。

arr = {"hello":"yes","because":"no"}
arr[0] =h

我想让它输出整个值而不仅仅是第一个字母

My code

        var clientContext = SP.ClientContext.get_current();
        var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
    // Get user properties for the target user.
    // To get the PersonProperties object for the current user, use the
    // getMyProperties method.
    MyProperties = peopleManager.getMyProperties();
    // Load the PersonProperties object and send the request.
    clientContext.load(MyProperties);
    clientContext.executeQueryAsync(getMyNewsChoicesSuccess, getMyNewsChoicesFail);
    },
    getMyNewsChoicesSuccess = function () {
        //get the news choice by actually fieldname
        var MyChoices = JSON.stringify(MyProperties.get_userProfileProperties().Value);
        $('#NBStest').text(MyChoices);
    },

你可以像这样从json字符串中获取第一个元素

JSON.parse(json_str)[0]

但是在这个例子中,第一个元素是"yes"它的索引是"hello"这意味着你不能通过索引0来获取第一个元素,但是你可以通过它的属性名来获取它,比如

arr.hello = "yes";
// or
arr['hello'] = "yes";

如果你想要得到hello也就是关键字,你必须使用这个循环

for (key in arr)
   console.log(key); 
// it will print 'hello' and then 'because'

它不再是数组了,它是字符串。Arr[0]将返回第一个字母。

如果你想从中获得对象,你需要解析它(尝试JSON)。解析)

JSON.stringify()做的正是它听起来的样子。它将javascript对象转换为字符串。所以当你做arr[0]时,你得到的是字符串中的第一个字母。如果您想要获得实际值,则需要将其转换回javascript对象。