Tengo una matriz como esta:
var array = [ { name:"string123", value:"this", other: "that" }, { name:"string2", value:"this", other: "that" }, { name:"string12", value:"ths", other: "that" }, ];Y ahora tengo una cadena como 'string12'. Ahora, con esta cadena, el resultado que quiero es encontrar los elementos que contienen esta cadena, que es como:
var array = [ { name:"string123", value:"this", other: "that" }, { name:"string12", value:"ths", other: "that" }, ];Esto es lo que he probado:
const search = (nameKey, myArray) => { for (var i = 0; i < myArray.length; i++) { var newArr = []; if (myArray[i].name.slice(0, nameKey.length + 1) === nameKey) { newArr.push(myArray[i]); } return newArr; } } var array = [ { name:"string123", value:"this", other: "that" }, { name:"string2", value:"this", other: "that" }, { name:"string12", value:"ths", other: "that" }, ]; var resultObject = search("string12", array); console.log(resultObject);Pero mi solución es devolver una matriz en blanco. ¿Dónde me estoy equivocando con esto?
Las siguientes cosas salieron mal en su implementación:
for ..slice() .return newArr debe estar fuera del bucle for . const search = (nameKey, myArray) => { var newArr = []; for (var i = 0; i < myArray.length; i++) { if (myArray[i].name.slice(0, nameKey.length) === nameKey) { newArr.push(myArray[i]); } } return newArr; } var array = [ { name:"string123", value:"this", other: "that" }, { name:"string2", value:"this", other: "that" }, { name:"string12", value:"ths", other: "that" }, ]; var resultObject = search("string12", array); console.log(resultObject);El uso Array#filter y String#includes :
const arr = [ { name:"string123", value:"this", other: "that" }, { name:"string2", value:"this", other: "that" }, { name:"string12", value:"ths", other: "that" } ]; const res = arr.filter(({ name }) => name.includes('string12')); console.log(res); Puede usar String#startsWith en lugar de includes si solo necesita verificar si el nombre comienza con la cadena.
Podría hacer esto con Array.filter y la función startsWith ( docs ). Si desea verificar la string12 en cualquier parte del name , use includes en lugar de startsWith
var array = [ { name:"string123", value:"this", other: "that" }, { name:"string2", value:"this", other: "that" }, { name:"string12", value:"ths", other: "that" }, ]; const filtered = array.filter(item => item.name.startsWith("string12")); console.log(filtered);