Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

arrays - Iterate over a Javascript Object and perfom conditional on values

So i have a JS Object like that :

let object =
    {
      "key1":"value1",
      "key2":"value2",
      "key3":"value3"
    }

For iterating, i use this : for (let i = 0; i < Object.keys(object).length; i++)

Now, what i want to do is basically this :

let value;
if (data === undefined || data === "") {
        value = []
} else if (data.includes(",")) {
    value = data.split(",")
} else if (data.includes(".")) {
    value = data.split(".")
} else {
    value = data.split(" ");
}

So, i tried Object.values(entries_array).split(",") but split is not an Object method. So if you can help me to find a solution. Thanks in advance.

Edit: Sorry, i'll try to describe more what i want to achieve. I want with the code, to obtain my object variable changed with the same keys but with the values splitted.

For example if the value has a comma, i want to split the value. If not, do nothing.

For now, i have this :

 let object =
    {
      "key1":"value1",
      "key2":"value2",
      "key3":"value3"
    }
const entries = Object.entries(object);
const entries_array = Object.fromEntries(entries)
let data_val;
for (let i = 0; i < Object.keys(entries_array).length; i++) {
    Object.values(entries_array).forEach(val => {
  if (val === undefined || val === "") {
        data_val = []
} else if (val.includes(",")) {
    data_val = val.split(",")
} else if (val.includes(".")) {
    data_val = val.split(".")
} else {
    data_val = val.split(" ");
}
});
}
return entries_array;
question from:https://stackoverflow.com/questions/65829829/iterate-over-a-javascript-object-and-perfom-conditional-on-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

function reassignValueAsArray(obj, [key, value]) {
  obj[key] = value.split(/s*[., ]s*/);
  return obj;
}
function reassignKeyValuesAsArray(obj) {
  return Object
    .entries(obj)
    .reduce(reassignValueAsArray, obj);
}

const sampleObject = {
  "key1": "value1,value1b",
  "key2": "value2.value2b",
  "key3": "value3 value3b",
  "key4": "value4.value4b,value4c value4d",
  "key5": "value5-value5b-value5c-value5d",
};
reassignKeyValuesAsArray(sampleObject);

console.log(sampleObject);
.as-console-wrapper { min-height: 100%!important; top: 0; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...