Необходим доступ к массиву объекта Child из родительского объекта в Javascript

1
PostResponseOutput(TextedValue):Promise<any>
{
var options = {
    method: 'POST',
    url: 'http://NHSSQLCHNE8105:8081/ctakes-web-rest/service/analyzejson? 
pipeline=default',
    headers: {
        'Accept': 'application/json',
        'Content-Type' : 'application/json'
    },
    body: TextedValue
};
await request(options, callback);
async function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        var info = await JSON.parse(body);    
}  
}}

Используя запросы npm, я получаю тело json и использую JSON.parse(body) Преобразует приведенный ниже JSON файл в список объектов. Мне нужно получить доступ к массиву, который находится в дочернем объекте. Но так как дочерний объект изменяется динамически на основе ввода, который мы предоставляем. Я не могу получить массив дочернего объекта в коде. Может ли кто-нибудь помочь в получении массива из объекта PARENT без доступа к объекту Child.

Мне нужно удалить динамически изменяющиеся дочерние объекты и получить доступ к его массиву из родительского объекта. Примечание. Объект PARENT не изменяется на основе ввода. он будет иметь значение или не основан на вводе

Файл JSON

{
// This is the Allergy Object. which doesn't have any Value for the input 
Admit
    "Allergy": {},
// This is the Others Object. which has 1 Value for the input Admit
    "Others": {
        **"Health Care Activity~T058~Hospital admission":** [
            "codingScheme: SNOMEDCT_US",
            "code: 32485007",
            "cui: C0184666",
            "semanticType: Health Care Activity",
            "tui: T058",
            "preferredtext: Hospital admission"
        ]
    },
// This is the AnatomicalSiteMention Object. which doesn't have any Value 
for the input Admit
    "AnatomicalSiteMention": {},
// This is the MedicationMention Object. which doesn't have any Value for the 
input Admit
    "MedicationMention": {},
// This is the DrugChangeStatusAnnotation Object. which doesn't have any 
Value for the input Admit
    "DrugChangeStatusAnnotation": {},
// This is the DrugChangeStatusAnnotation Object. which doesn't have any 
Value for the input Admit
    "StrengthAnnotation": {},
// This is the Request Object. which doesn't have any Value for the input 
Admit
    "Request": {},
// This is the FractionStrengthAnnotation Object. which doesn't have any 
Value for the input Admit
    "FractionStrengthAnnotation": {},
// This is the FrequencyUnitAnnotation Object. which doesn't have any Value 
for the input Admit
    "FrequencyUnitAnnotation": {},
// This is the DiseaseDisorderMention Object. which doesn't have any Value 
for the input Admit
    "DiseaseDisorderMention": {},
// This is the FamilyMember Object. which doesn't have any Value for the 
input Admit
    "FamilyMember": {},
// This is the SignSymptomMention Object. which doesn't have any Value for 
the input Admit
    "SignSymptomMention": {},
// This is the RouteAnnotation Object. which doesn't have any Value for the 
input Admit
    "RouteAnnotation": {},
// This is the DateAnnotation Object which doesn't have any Value for the 
input Admit
    "DateAnnotation": {},
// This is the MeasurementAnnotation Object. which doesn't have any Value for 
the input Admit
    "MeasurementAnnotation": {},
// This is the RelationDetails Object. which doesn't have 1 Child object 
Value  for the input Admit
    "RelationDetails": {
        **"RELATIONS:":** [
            "\n"
        ]
    },
// This is the TimeMention. which doesn't have 1 Child object Value  for the 
input Admit
    "TimeMention": {},
// This is the ProcedureMention. which doesn't have 1 Child object Value  for 
the input Admit
    "ProcedureMention": {},
// This is the StrengthUnitAnnotation object. which doesn't have 1 Child 
object Value  for the input Admit
    "StrengthUnitAnnotation": {},
// This is the Health Care activity Object. which doesn't have 1 Child object 
Value  for the input Admit
    "Health Care activity": {
        **"Hospital admission":** [
            "start:1",
            "end:3",
            "polarity:1",
            "[codingScheme: SNOMEDCT_US, code: 32485007, cui: C0184666, 
semanticType: Health Care Activity, tui: T058, preferredtext: Hospital 
admission]"
        ]
    },
// This is the AnalysisText object which doesn't have 1 Child object Value  
for the input Admit
    "AnalysisText": {
        **"AnalysisText":** [
            "admit\n  ",
            "admit\n  "
        ]
    }
}

Я выделил ** дочерние объекты, которые будут динамически изменяться на основе ввода. В настоящее время я дал Admit в качестве вклада в Postmantool

  • 0
    Вы просто пытаетесь найти массив в Others["Health Care Activity~T058~Hospital admission"] не зная строку " Health Care Activity~T058~Hospital admission ?"
  • 0
    @MarkMeyer Спасибо за ваш ответ .... да ... После синтаксического анализа json он создает другие как родительский объект, и внутри него он имеет дочерний объект медицинской активности (который динамически изменяет имя на основе входных данных) и имеет массив в что мне нужно предпочитаемое значение текста. Я пытаюсь получить предпочитаемое значение текста от родителя.
Теги:
javascript-objects

1 ответ

0
Лучший ответ

Вы можете получить все значения дочерних объектов, не зная ключей, используя Object.values. Это будет массив всех значений всех детей. Таким образом, в случае вашего объекта вы можете получить доступ к массиву с помощью:

let Admit = {
    "Allergy": {},
    "Others": {
        "Health Care Activity~T058~Hospital admission": [
                "codingScheme: SNOMEDCT_US",
                "code: 32485007",
                "cui: C0184666",
                "semanticType: Health Care Activity",
                "tui: T058",
                "preferredtext: Hospital admission"
            ]
    },
     "AnatomicalSiteMention": {}
     // etc...
}

let othersObj = Admit.Others
// children will have all the values of 'others' children
// you don't need to know 'Health Care Activity~T058~Hospital admission' 
let children = Object.values(othersObj)
console.log(children[0])

Вам просто нужно быть осторожным, чтобы вы знали, сколько детей может быть. Предполагалось, что есть только один, чтобы мы могли получить доступ к ним с children[0].

Ещё вопросы

Сообщество Overcoder
Наверх
Меню