Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

javascript - Determine if array element represents an object or a value

From a JSON object (containing stock data), I want to add certain elements to an array (in Google Sheets script editor):

var quote = JSON.parse(response.getContentText());

// Example of what quote object looks like:

{
    "quoteSummary": {
        "result": [
            {
                "Profile": {
                    "sector": "Technology",
                    "website": "www.test.com"
                },
                "Owners": [
                    {
                        "name": "Eric",
                        "age": "28"
                    },
                    {
                        "name": "Susan",
                        "age": "44"
                    }
                ],
                "Profit": 100,
                "Assets": 7000
            }
        ]   
    }
}

Here is my current approach to read only some specific values:

var arr   = [];

arr.push(quote.quoteSummary.result[0].Profile.sector); // Technology
arr.push(quote.quoteSummary.result[0].Owners[1].name); // Susan
arr.push(quote.quoteSummary.result[0].Profit);         // 100

But since there are many specific properties to read, I'd like to use a loop:

var quote = JSON.parse(response.getContentText());
var arr   = [];

var el = [
    ['Profile', 'sector'],
    ['Owners[1]', 'name'],
    ['Profit']
];

for (i = 0; i < el.length; i++)
{
    if (quote.quoteSummary.result[0][el[i][0]][el[i][1]] !== undefined)
    {
        arr.push(quote.quoteSummary.result[0][el[i][0]][el[i][1]].value);
    }
}

/*
Expected output (if I would loop through arr):
Technology
Susan
100
*/

The point is that different stocks, will have different properties. So el might define some non-existing elements or properties. Assume (in a bit of an other way of defining el -- as I wrote, I'm plexible here.. perhaps the paths are the easiest):

var el = [
    'Profile.website',
    'Profile.name',
    'Assets'
]

/*
Expected output:

www.test.com
                 <----- "name" doesn't exist!
7000

Notice that in this example, there is no property "name" in Profile,
so I'd like to add an empty element to arr
*/

But this does not work. What is a generic loop that accomplishes what I'm trying to do here? The array defining what I want can also be constructed differently if that helps. But the point is that I don't end up with a script like:

arr.push(quote.quoteSummary.result[0].Profile.something);
arr.push(quote.quoteSummary.result[0].Profile.something);
arr.push(quote.quoteSummary.result[0].Profile.something);
arr.push(quote.quoteSummary.result[0].Profile.something);
arr.push(quote.quoteSummary.result[0].Profile.something);
arr.push(quote.quoteSummary.result[0].Profile.something);
arr.push(quote.quoteSummary.result[0].Profile.something);
arr.push(quote.quoteSummary.result[0].Profile.something);
arr.push(quote.quoteSummary.result[0].Profile.something);
arr.push(quote.quoteSummary.result[0].Profile.something);
arr.push(quote.quoteSummary.result[0].Profile.something);
question from:https://stackoverflow.com/questions/65648843/determine-if-array-element-represents-an-object-or-a-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I recommend you use variable-length chains of property names. Each name in a given chain represents a deeper property. You can "dive" into an object through an arbitrary number of property names with code like this:

let dive = (obj, propertyNames) => {
  for (let pn of propertyNames) obj = obj[pn];
  return obj;
};

Now you can say:

let dive = (obj, propertyNames) => {
  for (let pn of propertyNames) obj = obj[pn];
  return obj;
};

let quote = {
  quoteSummary: {
    result: [
      {
        Profile: {
          sector: 'Technology',
          website: 'www.test.com'
        },
        Owners: [
          {
            name: 'Eric',
            age: '28'
          },
          {
            name: 'Susan',
            age: '44'
          }
        ],
        Profit: 100,
        Assets: 7000
      }
    ]
  }
};

// Here are the "variable-length property chains":
let el = [
  [ 'Profile', 'sector' ],
  [ 'Owners', 1, 'name' ],
  [ 'Profit' ]
];

// Here's how to combine `el`, `dive`, and your `quote` data to get a result:
let arr = el.map(propertyNames => dive(quote.quoteSummary.result[0], propertyNames));

console.log(arr);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...