¿Cómo recuperar la propiedad de una matriz de objeto y aquellos en un objeto separado usando JavaScript? -- javascript camp Relacionados El problema

How to retrieve property from an array of object and those in a seperate object using javascript?


0
vote

problema

Español

Quiero recuperar ciertas propiedades de la matriz de objeto y almacenarlo en una matriz.

La estructura de datos se ve a continuación,

  object_arr  [{…}]0:      first_property: "color"     id: 25     x: 10     y: 50     z: 56     _proto__: Objectlength: 1__proto__: Array(0)   

Quiero recuperar los valores X, Y y Z para que la salida sea como la salida a continuación

  (3) [10, 50, 56]     0: 10     1: 50     2: 56     length: 3 __proto__: Array(0)  so final_output[0] should give me 10, final_output[1] should give me 50 and final_output[2] should give 56   

¿Qué he probado?

  let final_output = object_arr.map(m => {        return [            m.x,            m.y,            m.z        ]    });   

La última portada se ve así,

  final_output [Array(3)]     0: (3) [10, 50, 56]     length: 1   the expected output is as below,   final_output (3) [10, 50, 56]      0: 10      1: 50      2: 56      length: 3   

¿Cómo puedo arreglar esto? Podría alguien ayudarme con esto. gracias.

Original en ingles

i want to retrieve certain properties from the array of object and store it in a array.

the data structure looks like below,

object_arr  [{xe2x80xa6}]0:      first_property: "color"     id: 25     x: 10     y: 50     z: 56     _proto__: Objectlength: 1__proto__: Array(0) 

i want to retrieve x, y and z values so the output should be like below

(3) [10, 50, 56]     0: 10     1: 50     2: 56     length: 3 __proto__: Array(0)  so final_output[0] should give me 10, final_output[1] should give me 50 and final_output[2] should give 56 

what i have tried?

let final_output = object_arr.map(m => {        return [            m.x,            m.y,            m.z        ]    }); 

the final_output looks like this,

final_output [Array(3)]     0: (3) [10, 50, 56]     length: 1   the expected output is as below,   final_output (3) [10, 50, 56]      0: 10      1: 50      2: 56      length: 3 

how can i fix this. could someone help me with this. thanks.

  
         
         

Lista de respuestas

0
 
vote
vote
La mejor respuesta
 

Si su matriz solo contiene un objeto, puede agregar sus propiedades directamente a una matriz así:

  const object_arr = [{first_property:"color",id:25,x:10,y:50,z:56}];  const [{x, y, z}] = object_arr; // use destructuring to get the object keys from the array  const res = [x, y, z]; // create an array containing x, y, z properties  console.log(res);  

Si su matriz puede contener múltiples objetos, puede usar .flatMap() al asignar sus propiedades a una matriz, que luego caerá en una matriz resultante más grande. De esta manera, todos x , y y z PROPIEDADES (de todos los objetos) se asignarán a una matriz de salida más grande:

  const object_arr = [{first_property:"color",id:25,x:10,y:50,z:56}];  const res = object_arr.flatMap(o => [o.x, o.y, o.z]); console.log(res);   
 

If your array only contains the one object, you can add its properties directly into an array like so:

const object_arr = [{first_property:"color",id:25,x:10,y:50,z:56}];  const [{x, y, z}] = object_arr; // use destructuring to get the object keys from the array  const res = [x, y, z]; // create an array containing x, y, z properties  console.log(res);

If your array can contain multiple objects, you could use .flatMap() by mapping your properties to an array, which will then fall into a larger resulting array. This way, all x, y and z properties (of all objects) will be mapped to one larger output array:

const object_arr = [{first_property:"color",id:25,x:10,y:50,z:56}];  const res = object_arr.flatMap(o => [o.x, o.y, o.z]); console.log(res);
 
 
   
   
1
 
vote

Haga esto:

  let object_arr = { first_property: "color", id: 25, x: 10, y: 50, z: 56} let final_output = [object_arr.x, object_arr.y, object_arr.z];   
 

Do this:

let object_arr = { first_property: "color", id: 25, x: 10, y: 50, z: 56} let final_output = [object_arr.x, object_arr.y, object_arr.z]; 
 
 
   
   
1
 
vote

Esto es bastante simple. Creo que su confusión está derivada de tratar de trabajar con la matriz de entrada en su conjunto. Si solo desea los datos de su primer elemento, no necesita import re def check_password(chars, min_chars=6, max_chars=12): class Password: pass Password.has_uppercase = bool(re.search(r'[A-Z]', chars)) Password.has_lowercase = bool(re.search(r'[a-z]', chars)) Password.has_numbers = bool(re.search(r'[0-9]', chars)) if not min_chars <= len(chars) <= max_chars: print("Password needs to be between %s and %s characters." % (min_chars, max_chars)) return /* Return a list of only my attributes of the Password class. */ return [t for t in vars(Password).items() if not t[0].startswith("__")] if __name__ == "__main__": meanings = {0: "unacceptable", 1: "Weak", 2: "Medium", 3: "Strong"} while True: chars = input(' Enter a password: ') results = check_password(chars) if results: /* Points are equal to how many tests are successful */ points = len([p[0] for p in results if p[1] is True]) /* Print out the results to the console */ print(" Password strength is %s. " % meanings.get(points)) for condition, result in results: print("{0:<15} {1} {2}".format(condition, ":", bool(result))) break 0 . Simplemente diríjase directamente con import re def check_password(chars, min_chars=6, max_chars=12): class Password: pass Password.has_uppercase = bool(re.search(r'[A-Z]', chars)) Password.has_lowercase = bool(re.search(r'[a-z]', chars)) Password.has_numbers = bool(re.search(r'[0-9]', chars)) if not min_chars <= len(chars) <= max_chars: print("Password needs to be between %s and %s characters." % (min_chars, max_chars)) return /* Return a list of only my attributes of the Password class. */ return [t for t in vars(Password).items() if not t[0].startswith("__")] if __name__ == "__main__": meanings = {0: "unacceptable", 1: "Weak", 2: "Medium", 3: "Strong"} while True: chars = input(' Enter a password: ') results = check_password(chars) if results: /* Points are equal to how many tests are successful */ points = len([p[0] for p in results if p[1] is True]) /* Print out the results to the console */ print(" Password strength is %s. " % meanings.get(points)) for condition, result in results: print("{0:<15} {1} {2}".format(condition, ":", bool(result))) break 1111111 :

  import re  def check_password(chars, min_chars=6, max_chars=12):     class Password: pass      Password.has_uppercase = bool(re.search(r'[A-Z]', chars))     Password.has_lowercase = bool(re.search(r'[a-z]', chars))     Password.has_numbers = bool(re.search(r'[0-9]', chars))      if not min_chars <= len(chars) <= max_chars:         print("Password needs to be between %s and %s characters." % (min_chars, max_chars))         return        /* Return a list of only my attributes         of the Password class. */       return [t for t in vars(Password).items() if not t[0].startswith("__")]    if __name__ == "__main__":     meanings = {0: "unacceptable", 1: "Weak", 2: "Medium", 3: "Strong"}      while True:         chars = input(' Enter a password: ')         results = check_password(chars)         if results:              /* Points are equal to how many tests are successful */             points = len([p[0] for p in results if p[1] is True])              /* Print out the results to the console */             print(" Password strength is %s. " % meanings.get(points))              for condition, result in results:                 print("{0:<15} {1} {2}".format(condition, ":", bool(result)))             break 2  
 

This is quite simple. I think your confusion is stemming from trying to work with the input array as a whole. If you only want the data from its first element, you don't need map. Just address it directly with [0]:

let object_arr = [{ first_property: "color", id: 25, x: 10, y: 50, z: 56}]  let final_output = [object_arr [0] .x, object_arr [0] .z, object_arr [0] .z];    console .log (final_output)
 
 
0
 
vote

puedes ver claramente: import re def check_password(chars, min_chars=6, max_chars=12): class Password: pass Password.has_uppercase = bool(re.search(r'[A-Z]', chars)) Password.has_lowercase = bool(re.search(r'[a-z]', chars)) Password.has_numbers = bool(re.search(r'[0-9]', chars)) if not min_chars <= len(chars) <= max_chars: print("Password needs to be between %s and %s characters." % (min_chars, max_chars)) return /* Return a list of only my attributes of the Password class. */ return [t for t in vars(Password).items() if not t[0].startswith("__")] if __name__ == "__main__": meanings = {0: "unacceptable", 1: "Weak", 2: "Medium", 3: "Strong"} while True: chars = input(' Enter a password: ') results = check_password(chars) if results: /* Points are equal to how many tests are successful */ points = len([p[0] for p in results if p[1] is True]) /* Print out the results to the console */ print(" Password strength is %s. " % meanings.get(points)) for condition, result in results: print("{0:<15} {1} {2}".format(condition, ":", bool(result))) break 3 que es la matriz de matriz. Entonces, para obtener el valor 10, deberá hacer: import re def check_password(chars, min_chars=6, max_chars=12): class Password: pass Password.has_uppercase = bool(re.search(r'[A-Z]', chars)) Password.has_lowercase = bool(re.search(r'[a-z]', chars)) Password.has_numbers = bool(re.search(r'[0-9]', chars)) if not min_chars <= len(chars) <= max_chars: print("Password needs to be between %s and %s characters." % (min_chars, max_chars)) return /* Return a list of only my attributes of the Password class. */ return [t for t in vars(Password).items() if not t[0].startswith("__")] if __name__ == "__main__": meanings = {0: "unacceptable", 1: "Weak", 2: "Medium", 3: "Strong"} while True: chars = input(' Enter a password: ') results = check_password(chars) if results: /* Points are equal to how many tests are successful */ points = len([p[0] for p in results if p[1] is True]) /* Print out the results to the console */ print(" Password strength is %s. " % meanings.get(points)) for condition, result in results: print("{0:<15} {1} {2}".format(condition, ":", bool(result))) break 4 O import re def check_password(chars, min_chars=6, max_chars=12): class Password: pass Password.has_uppercase = bool(re.search(r'[A-Z]', chars)) Password.has_lowercase = bool(re.search(r'[a-z]', chars)) Password.has_numbers = bool(re.search(r'[0-9]', chars)) if not min_chars <= len(chars) <= max_chars: print("Password needs to be between %s and %s characters." % (min_chars, max_chars)) return /* Return a list of only my attributes of the Password class. */ return [t for t in vars(Password).items() if not t[0].startswith("__")] if __name__ == "__main__": meanings = {0: "unacceptable", 1: "Weak", 2: "Medium", 3: "Strong"} while True: chars = input(' Enter a password: ') results = check_password(chars) if results: /* Points are equal to how many tests are successful */ points = len([p[0] for p in results if p[1] is True]) /* Print out the results to the console */ print(" Password strength is %s. " % meanings.get(points)) for condition, result in results: print("{0:<15} {1} {2}".format(condition, ":", bool(result))) break 5 Luego import re def check_password(chars, min_chars=6, max_chars=12): class Password: pass Password.has_uppercase = bool(re.search(r'[A-Z]', chars)) Password.has_lowercase = bool(re.search(r'[a-z]', chars)) Password.has_numbers = bool(re.search(r'[0-9]', chars)) if not min_chars <= len(chars) <= max_chars: print("Password needs to be between %s and %s characters." % (min_chars, max_chars)) return /* Return a list of only my attributes of the Password class. */ return [t for t in vars(Password).items() if not t[0].startswith("__")] if __name__ == "__main__": meanings = {0: "unacceptable", 1: "Weak", 2: "Medium", 3: "Strong"} while True: chars = input(' Enter a password: ') results = check_password(chars) if results: /* Points are equal to how many tests are successful */ points = len([p[0] for p in results if p[1] is True]) /* Print out the results to the console */ print(" Password strength is %s. " % meanings.get(points)) for condition, result in results: print("{0:<15} {1} {2}".format(condition, ":", bool(result))) break 6

 

You can clearly see : final_output [Array(3)] 0: (3) [10, 50, 56] which is array of array. So to get value 10 you will have to do: final_output[0][0]. Or output=final_output[0]; Then output[0]

 
 

Relacionados problema

54  ¿La diferencia entre las dos funciones? ("Función X" vs "var x = función") [duplicar]  ( The difference between the two functions function x vs var x function ) 
Esta pregunta ya tiene respuestas aquí : Cerrado hace 8 años . posible duplicado: javascri...

0  LazyWeb: necesita Javascript que elimina los elementos de LI basados ​​en la clase visitada de un elemento  ( Lazyweb need javascript that removes li elements based on visited class of a el ) 
Tengo esta página que tiene muchos datos que no necesito, ya que ya he hecho clic en él, pero se repite a menudo, así que tengo que buscar visualmente el azul...

2  ¿Hay una biblioteca de gráficos del lado del cliente (JavaScript) que no requiera un servidor? [cerrado]  ( Is there a client side javascript graph library that doesnt require a server ) 
cerrado. Esta pregunta no cumple con pautas de desbordamiento de pila . Actualmente no está aceptando respuestas. ...

0  ¿Cómo puedo pasar un objeto anónimo de JavaScript de Java a JavaScript en GWT?  ( How can i pass an anonymous javascript object from java to javascript in gwt ) 
Estoy creando una envoltura GWT alrededor de una biblioteca de JavaScript. Una de las funciones de JavaScript realiza un objeto anónimo como su argumento, por...

0  Deshacerse del disco en el artículo de la lista  ( Getting rid of disc in list item ) 
Estoy desarrollando un sitio usando jquery, y jquery ui Tabs. Por alguna razón, mis pestañas (lista desordenada) están mostrando sus balas en todos los navega...

142  ¿Cómo detectar cuál de las fuentes definidas se utilizó en una página web?  ( How to detect which one of the defined font was used in a web page ) 
Supongamos que tengo la siguiente regla de CSS en mi página: body { font-family: Calibri, Trebuchet MS, Helvetica, sans-serif; } ¿Cómo podría detec...

44  Cotizaciones triples? ¿Cómo delimito un parámetro de cadena de JavaScript de datos de datos en ASP.NET?  ( Triple quotes how do i delimit a databound javascript string parameter in asp n ) 
¿Cómo delimito un parámetro de cadena con límite de datos de JavaScript en un evento de anclaje 9988777661 ? Tengo una etiqueta de anclaje en un control d...

1279  ¿Cómo pongo / no tomar una cookie con jQuery?  ( How do i set unset a cookie with jquery ) 
¿Cómo configuro y no prestar atención a una cookie utilizando jQuery, por ejemplo, cree una cookie llamada test y configure el valor en 1 ? ...

35  Validación del lado del cliente de ASP.NET  ( Asp net custom client side validation ) 
Tengo una función de validación personalizada en JavaScript en un control de usuario en un sitio web .NET 2.0 que comprueba para ver que la tarifa pagada no e...

0  JavaScript: detectando cuando ninguna de las dos entradas se ha centrado  ( Javascript detecting when neither of two inputs has focus ) 
Quiero que se llame una cierta función cuando ninguna de las dos entradas en la página se ha centrado. Si el usuario simplemente cambia de una entrada a la ot...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos