简体   繁体   English

使用内部的一些键和对象数组迭代 object

[英]Iterate over object with some keys and array of objects inside

Assuming I have this data format:假设我有这种数据格式:

const matchedProperty = "property1"

const jsonObject = {
    "property1": {
        param1: '',
        param2: '',
        param3: '',
        data: [
            {key: value},
            {key: value},
            {key: value},
            {key: value}
        ],
        param4: ''
    },
    "propery2": {
        param1: '',
        param2: '',
        param3: '',
        data: [
            {key: value},
            {key: value},
            {key: value},
            {key: value}
        ],
        param4: ''
    }

}

How can I check if the property exists inside this json and after that how can I extract only data[{}] and param1 for example?如何检查此 json 中是否存在该属性,然后如何仅提取 data[{}] 和 param1?

Can't think of something that would be helpful and working想不出有用且有效的东西

Title doesn't match with body, so here's iteration and direct access:标题与正文不匹配,所以这里是迭代和直接访问:

Iterating over Objects: for..in迭代对象: for..in

let object = { a: 1, b: 2, c: 3 }

for (let key in object) {
  console.log(key + ' = ' + object[key])
}

// a = 1
// b = 2
// c = 3

Iterating over Arrays: for..of迭代 Arrays: for..of

let vector = ['a', 'b', 'c']

for (let element of vector) {
  console.log(element)
}

// a
// b
// c

Accessing Array Values At Position在 Position 访问数组值

let vector = ['a', 'b', 'c']
console.log(vector[0]) // a
console.log(vector[1]) // b
console.log(vector[2]) // c
console.log(vector[3]) // undefined

Accessing Object Values By Key按键访问 Object 值

let object = { a: 1, b: 2, c: 3 }
console.log(object["a"]) // 1
console.log(object.a)    // 1
console.log(object["b"]) // 2
console.log(object.b)    // 2
console.log(object["c"]) // 3
console.log(object.c)    // 3
console.log(object["d"]) // undefined
console.log(object.d)    // undefined

Check if Exists检查是否存在

Since undefined won't trigger on an if-condition but values will, just write if object["key"] ;由于undefined不会在 if 条件下触发,但值会触发,只需编写if object["key"] ; it will execute the next code block if the key exists, otherwise it won't.如果密钥存在,它将执行下一个代码块,否则不会。 (Not suggested practice.) (不建议练习。)

something like this?像这样的东西?

 const matchedProperty = "property1" const jsonObject = { "property1": { param1: '', param2: '', param3: '', data: [ {key: 'value'}, {key: 'value'}, {key: 'value'}, {key: 'value'} ], param4: '' }, "propery2": { param1: '', param2: '', param3: '', data: [ {key: 'value'}, {key: 'value'}, {key: 'value'}, {key: 'value'} ], param4: '' } } const result = jsonObject.hasOwnProperty(matchedProperty)?{param1: jsonObject[matchedProperty].param1, data: jsonObject[matchedProperty].data}:{} console.log(result)

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

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