I would like only data containing a certain string to be sent from my array to another array for example
test=something
test1=something
test=testsadsad
If my array contains test=
My new array will be ['something', 'testsadsad']
This is my code.
let data = Object.values(args);
let serializedData = data.join("\n");
let newArray = [];
for (let i = 0; i < data.length; i ) {
if (data[i].includes("test=") === true) {
console.log(data[i])
newArray.push(data[i].split("test="));
}
}
CodePudding user response:
You can modify your logic like this
//simulated data
const data = [
"test=something",
"test1=something",
"test=testsadsad",
]
let newArray = [];
for (let i = 0; i < data.length; i ) {
//`key` is `test` and `value` is `something`
const [key, value] = data[i].split("=") //splitted by `=`
if (key === "test") {
newArray.push(value);
}
}
console.log(newArray)
CodePudding user response:
You are not formatting the data correctly when pushing onto the array.
let data = Object.values(args);
let newArray = [];
for (let i = 0; i < data.length; i ) {
if (data[i].includes("test=") === true) {
console.log(data[i])
// Note It looks like your problem is here
newArray.push(data[i].replace("test=", ''));
}
}
CodePudding user response:
If your input array is data
then this will return the desired output:
let output = data
.filter(item => item.includes("test="))
.map(item => item.split("test=")[1])
This filters the array by selecting all items that include test=
and then maps each result to the substring after test=
.