Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How to create an object with properties in the array from the string?

I want to create objects with properties in an array by string. I'm extracting "name" from string and "data" without round brackets and trying to create objects in the array with the property "name" and property "data". But actual result differs from expected, please help to solve

const names = ["name1 /2 (data1)", "name1 /2 (data2)", "name2 /1 (data1)"]
const flag = true

names.forEach(name => {
    console.log(getStructuredDataFromNames(name))
})

function getStructuredDataFromNames(name) {
    const names = {}
    // extract name from string and conver to valid format - 'name1'
    const formattedName = name.substr(0, name.indexOf("/")).replace(/s+/g, "")
    // extract data from string and conver to valid format - 'data1'
    const formattedData = name.match(/((.*))/).pop()

    const reference = {
        formattedData,
        flag
    }
    // if no name then create a new property by this name
    if (!names[name]) {
        names[name] = [{
            data: [reference]
        }]
    } else {
        // if object have name but name have more then 1 data then push this data to array
        names[name].push(reference)
    }
    const result = Object.keys(names)
    return result.map(el => ({
        name: el,
        data: names[el]
    }))
}

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

1 Reply

0 votes
by (71.8m points)

Although the code is not that clean, it can do the job. My flow is first to remove the spaces, and then split the name and the data, remove the number before the data and remove (). If "formattedNames" already have the same "name" object, push the data to the "name" object.

const names = ["name1 /2 (data1)", "name1 /2 (data2)", "name2 /1 (data1)"]
const formattedNames = []

names.forEach(value =>{
  const processedName = value.replace(/ /g,'').split("/")
  const formattedName = formattedNames.find((object)=>{ return object.name === processedName[0]})
  const formattedData = processedName[1].split("(")[1].replace(")","")
  if (!formattedName) {
    formattedNames.push({name: processedName[0],data: [{flag: true, formattedData}]})
  } else {
    formattedName.data.push({flag: true, formattedData})
  }
})

console.log(formattedNames)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...